(C++继承)将具有公共父级的对象存储在stl容器中
(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 Zn";
}
int x;
};
class A: public Z
{
public:
virtual void echo()
{
cout << "this is An";
}
};
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
的对象(因为容器确实期望并存储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>>
。
相关文章:
- 如何使用 stl 容器有效地存储对象?(即根据其字段的值进行搜索)
- 线程上下文上的静态存储对象优化
- OOP - 存储对象和服务接口
- 为什么存储对象地址在缓冲区中会导致内存泄漏并删除它们
- 是否保证在销毁所有线程本地存储对象后销毁全局对象
- 使用列表存储对象
- 在c++中存储一个对象或不存储对象的首选方式是什么
- 更好的是:存储对象与存储指针
- 应用程序使用QMAP存储对象时停止响应
- 使用堆栈存储对象
- 如何在 std::map 中存储"对象类型"?
- 我应该如何存储对象
- 在 c++ 中存储对象的最佳策略是什么,确保名称唯一并能够在以后有效地检索它们
- 用于存储对象列表的最佳标准类
- 在C++中存储对象地址的数据结构
- 函子如何维护/存储对象的状态
- 我如何定义一个向量,并用C++在其中存储对象
- 存储对象以备将来使用(在重新启动程序时)
- C++/JNI-存储对象(jobject)在向量和数组中发生意外更改,C++或JNI问题
- 在多个容器中存储对象的最佳实践