【发布时间】:2014-04-01 15:00:06
【问题描述】:
我想在 C++ 中创建一个 Parent 类型的集合,在其中添加不同的子类,例如 Child 和 Child2,然后获取 X 子类的所有元素。我尝试了一个向量,但它碰巧根据this answer 破坏了多态性。如果我使用指针集合,我将不得不按顺序对其进行迭代,检查每个元素的类,是否有更好/更有效的解决方案?
这是一个示例代码:
class Parent
{
public:
int id;
Parent(){ id = 8; }
};
class Child: public Parent
{
int foo;
public:
Child(int n){ foo= n; }
};
class Child2: public Parent
{
int bar;
public:
Child2(int n){ bar= n; }
};
伪代码:
GenericCollection<Parent> collection; //Full of elements Child and Child2.
这是我要实现的方法:
collection.getElements<Child2>();
感谢一切。
【问题讨论】:
标签: c++ inheritance collections polymorphism stdvector