[英](C++ inheritance) storing objects with common parent in stl container
我将具有公共父对象的对象存储在stl容器(实际上是堆栈)中,但是在对象内部的对象上调用虚拟函数会导致在此公共父对象中调用实现。 查看演示代码:
#include <iostream>
#include <stack>
using namespace std;
class Z
{
public:
virtual void echo()
{
cout << "this is Z\n";
}
int x;
};
class A: public Z
{
public:
virtual void echo()
{
cout << "this is A\n";
}
};
int main()
{
A a;
a.x = 0;
Z z;
z.x = 100;
stack<Z> st;
st.push(a);
st.top().echo(); // prints "This is Z"
cout << "x = " << st.top().x << endl; // prints 0
st.push(z);
st.top().echo(); // prints "This is Z"
cout << "x = " << st.top().x << endl; // prints 100
return 0;
}
通常,对象容器和多态性不会混合在一起:将类型A
对象推入容器中时,会将它们切片为Z
类型A
对象(因为容器实际上是在等待并存储sizeof(Z)
对象)
使用std::stack<Z*>
或std::stack<std::unique_ptr<Z>>
来操纵指向基类的指针。
另请参阅: C ++中的切片问题是什么?
您有切片 :
您应该使用std::stack<Z*>
或std::stack<std::unique_ptr<Z>>
。
您观察到的是切片 。 您的堆栈存储了Z
对象,因此即使您构造一个A
对象,也不会将其存储在堆栈中-一个Z
对象将由A
构造并存储。
如果要多态,则不能按值存储在容器中。 使用stack<unique_ptr<Z>>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.