传递引用C++,指针的向量.这是怎么回事?

Pass By Reference C++, Vector of pointers. What is happening here?

本文关键字:向量 怎么回事 指针 引用 C++      更新时间:2023-10-16

我认为没有任何问题可以指出我正在寻找的解释。

在这个例子中(ABC 类中的 tryme(( 函数(,为什么在创建对象时执行父级的 myfunction,并且它的引用直接作为参数传递给函数。

class parent
{
public:
int abc;
parent(){};
~parent(){};
virtual void myfunction(void)
{
abc = 5;
output("parent myfunction abc %d", abc);
};
};
class child :public parent
{
public:
int abc;
child(int val):abc(val){};
child(){};
~child(){};
virtual void myfunction(void)
{
output("child myfunction abc %d", abc);
}
};
class ABC
{
std::vector<parent *> pvec;
void test(parent* t)
{
pvec.pushback(t);
}; 
void tryme()
{
child c1 = child(3);
child c2 = child(6);
ABC::test(&c1); <-------- this executed child - I understand
ABC::test(&c2); <-------- this executed child - I understand
ABC::test(&child(9)); <-------- this executed parent - I dont understand
ABC::test(&child(11));<-------- this executed parent - I dont understand
for each (auto it in pvec)
{
it->myfunction();
}
}
}

输出为

child myfunction abc 3
child myfunction abc 6
parent myfunction abc 5
parent myfunction abc 5

两者之间有什么区别 child c1 = child(3); &c1;

&child(3)

谢谢

有几件事...您的标题表明您是"通过参考"。 您实际上是在通过"通过指针"。

另外,当您致电时

ABC::test(&c1);

您正在获取堆栈变量c1的地址并将其传递给函数。 然后,数组存储对象的地址。 对于前两个调用,这是可以的。

但。。。当您致电时

ABC::test(&child(9));

您正在创建一个临时对象,该对象仅在函数调用期间有效,并将其地址传递给函数,然后函数存储指向临时对象的"悬空"指针。

函数调用结束后,对象将被销毁。 通过数组仍然按住指向现在垃圾内存的指针。

它稍后调用"Parent"函数调用的事实只是完全随机的、未定义的行为。 它可以很容易地打印出生命的意义,或者在过去,炸毁你的显示器。 :)