(C++ 继承)在 stl 容器中存储具有公共父级的对象 [英] (C++ inheritance) storing objects with common parent in stl container

查看:24
本文介绍了(C++ 继承)在 stl 容器中存储具有公共父级的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 stl 容器(实际上是堆栈)中存储了一个具有公共父级的对象,但是在它内部的对象上调用虚拟函数会导致调用这个公共父级中的实现.查看演示代码:

I am storing an objects with common parent in stl container (actually stack), but calling a virtual function on object inside of it results in calling an implementation in this common parent. See demo code:

#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 类型的对象(因为容器确实在期待并存储 sizeof(Z) 的对象)

In general, containers of objects and polymorphism don't mix : You are slicing your objects of type A into objects of type Z when you push them in the container (because the container is really expecting and storing objects of sizeof(Z))

使用 std::stackstd::stack> 来操作指向您的基类的指针.

Use std::stack<Z*>, or std::stack<std::unique_ptr<Z>> to manipulate pointers to your base class.

另见:C++ 中的切片问题是什么?

这篇关于(C++ 继承)在 stl 容器中存储具有公共父级的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆