(C++继承)将具有公共父级的对象存储在stl容器中

(C++ inheritance) storing objects with common parent in stl container

本文关键字:存储 对象 stl 继承 C++      更新时间:2023-10-16

我将一个具有公共父级的对象存储在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>>