我不認爲有任何問題指出我要找的解釋。通過引用傳遞C++,指針的向量。這裏發生了什麼?
在此示例中(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)
感謝
之間的不同
'test(&child(9));'會將一個懸掛指針存儲到臨時'child'對象,該對象在'test'返回後被銷燬。所以你在這裏面對UB。 – VTT
c1和c2並不好多少。 – 2017-08-01 22:28:15
你確定它被執行了嗎?我可以在xcode ABC :: test(&child(9))中看到警告; //獲取類型爲「child」的臨時對象的對象 –