通过引用 C++,指针向量传递。这里发生了什么?
Pass By Reference C++, Vector of pointers. What is happening here?
我认为没有任何问题指出我正在寻找的解释。
在此示例中(ABC class 中的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)
谢谢
几件事...你的头衔表明你是 "Passing by Reference"。你实际上超过了 "By Pointer"。
此外,当您致电
ABC::test(&c1);
您正在获取堆栈变量 c1
的地址并将其传递给您的函数。然后您的数组存储对象的地址。这对于前两个调用是可以的。
但是...当你打电话给
ABC::test(&child(9));
您正在创建一个仅在函数调用期间有效的临时对象,并将其地址传递给该函数,然后该函数存储一个指向该临时对象的 "dangling" 指针。
当函数调用结束时,对象被销毁。通过数组仍然持有指向现在垃圾内存的指针。
它稍后调用 "Parent" 函数调用的事实完全是随机的、未定义的行为。它可以很容易地打印出生命的意义,或者在过去,炸掉你的显示器。 :)
我认为没有任何问题指出我正在寻找的解释。
在此示例中(ABC class 中的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)
谢谢
几件事...你的头衔表明你是 "Passing by Reference"。你实际上超过了 "By Pointer"。
此外,当您致电
ABC::test(&c1);
您正在获取堆栈变量 c1
的地址并将其传递给您的函数。然后您的数组存储对象的地址。这对于前两个调用是可以的。
但是...当你打电话给
ABC::test(&child(9));
您正在创建一个仅在函数调用期间有效的临时对象,并将其地址传递给该函数,然后该函数存储一个指向该临时对象的 "dangling" 指针。
当函数调用结束时,对象被销毁。通过数组仍然持有指向现在垃圾内存的指针。
它稍后调用 "Parent" 函数调用的事实完全是随机的、未定义的行为。它可以很容易地打印出生命的意义,或者在过去,炸掉你的显示器。 :)