繁体   English   中英

(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 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM