(C++ 继承)在 stl 容器中存储具有公共父级的对象 [英] (C++ inheritance) storing objects with common parent in stl container
问题描述
我在 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类型的对象code> 将它们推入容器时将它们转换为
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::stack
或 std::stack
来操作指向您的基类的指针.
Use std::stack<Z*>
, or std::stack<std::unique_ptr<Z>>
to manipulate pointers to your base class.
这篇关于(C++ 继承)在 stl 容器中存储具有公共父级的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!