C ++ std容器-没有指针的多态性.是否有可能? [英] C++ std containers - polymorphism without pointers. Is it possible?
问题描述
是否可以在不使用指针的情况下保持任何 std c ++容器中派生类的知识,从而动态地从容器中转换返回值?我知道我可以创建向量或某些基类类型的指针,并保留它们的子类.但是问题是我必须使用指针吗?
Is it possible to maintain knowledge of the derived class in any std c++ container without using pointers, dynamically casting return values from the container? I know I can create a vector or what ever of pointers of some base class type, and have them retain their sub classes. But the question is do I have to use pointers?
示例:
struct A {
int x = 0, y = 0, z = 0;
virtual void foo() { cout << "A" << endl; };
};
struct B : public A {
int a = 1, b = 1, c = 1;
virtual void foo() { cout << "B" << endl; };
};
int main() {
<SOMECONTAINER><A> a(2);
a[0] = A();
a[1] = B();
B * p;
B& n = dynamic_cast<B&>(a[1]); // Always throws?
p = dynamic_cast<B*>(&a[1]); // Always zero?
cout << p << endl;
}
推荐答案
是的,您必须使用指针.否则,尝试将B
放入A
的容器中会导致切片:B
被切成A
(这不仅限于容器,如果执行A a = B()
或将B
传递给期望A
).
Yes, you do have to use pointers. Otherwise, attempting to put a B
into a container of A
results in slicing: the B
gets cut down into an A
(this is not limited to containers, the exact same thing happens if you do A a = B()
or if you pass a B
to a function expecting an A
).
当您稍后将其取出时,它是一个A
,它完全不知道其谱系包括类型为B
的杰出祖先-无论您以何种方式看待A
,您都可以使其成为B
.
When you later take it back out, it's an A
that has absolutely no knowledge its lineage includes an illustrious forefather of type B
-- and no matter what way you look at an A
, you can't make it a B
.
这篇关于C ++ std容器-没有指针的多态性.是否有可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!