传递引用C++,指针的向量.这是怎么回事?
Pass By Reference C++, Vector of pointers. What is happening here?
我认为没有任何问题可以指出我正在寻找的解释。
在这个例子中(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"函数调用的事实只是完全随机的、未定义的行为。 它可以很容易地打印出生命的意义,或者在过去,炸毁你的显示器。 :)
相关文章:
- 使用递归的数组的最小值.这是怎么回事
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?
- 绕道重铸瓷砖层是怎么回事
- 架 (U+67B6) 与en_US不符.UTF-8.这是怎么回事?
- R 中的算术在数字上比整数更快。这是怎么回事?
- 我的代码运行良好,但现在当尝试将其制作成模板时,我遇到了许多看似无关的错误。这是怎么回事?
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- 弄清楚这段代码是怎么回事(递归下降案例研究)
- 分配器密集和稀疏是怎么回事?
- 传递引用C++,指针的向量.这是怎么回事?
- __vector_base_common是怎么回事?
- (对象)不命名类型.怎么回事
- 变量已在 .obj 中定义;这是怎么回事?
- Sublime上的EasyClangComplete是怎么回事?
- 重复输出的类型是怎么回事,它如何区分迭代次数和 Ascii 代码?
- 标准::地图使用.这是怎么回事?核心转储?我做得不正确?
- llvm libcxx的源代码是怎么回事?
- 这一行是怎么回事: istringstream is( line );
- "enable_if"使编译器很难生成可读的错误消息,这是怎么回事