为简单起见
class Parent {}
class Child1 : Parent {}
class Child2 : Parent {}
Run Code Online (Sandbox Code Playgroud)
在其他地方,我创建了Child1和Child2的实例,并将其存储在Parent下的相同向量中:
// . . . in .h file, for example
vector<Parent> vector_of_parent;
// . . . in one particular method
Child1 c1;
Child2 c2;
vector_of_parent.push_back(c1);
vector_of_parent.push_back(c2);
// . . .
Run Code Online (Sandbox Code Playgroud)
然后在另一种有权访问的方法中vector_of_parent,我试过了
void doSomething(Parent& some_child) {
// wrapped in a try block somehow...
Child1& c = dynamic_cast<Child1&> some_child;
// do something if the cast is successful
}
void otherMethod() {
doSomething(vector_of_parent.at(0)); // vector_of_parent.at(0) is a Child1
}
Run Code Online (Sandbox Code Playgroud)
当我调用otherMethod()时为什么会有std:bad_cast?
你std::vector被宣布为std::vector<Parent>.它仅包含以下实例Parent- 当您插入Child1和Child2实例时,它们会被切片.
如果要使用具有公共基类的多态对象向量Parent,则需要使用指针容器(或者,为了便于生命周期和内存管理,使用智能指针).
要考虑的适当容器类型包括std::vector<Parent*>,std::vector<std::tr1::shared_ptr<Parent> >和boost::ptr_vector<Parent>.
std::vector<Parent*>除非你对手动内存管理非常熟悉,否则我建议不要这样做.
此外,您需要使用公共继承而不是私有,并且基类必须具有虚拟析构函数.我假设你为了简洁而把它们留下了.
小智 6
当你说:
vector<Parent> vector_of_parent;
Run Code Online (Sandbox Code Playgroud)
你创建一个父矢量 - 它不可能包含子对象.如果你想要一个多态C++容器,它必须包含基类指针.你的动态演员表失败了,因为你应用它的东西总是Parent而不是Child.
此外,您的代码并不清楚,但为了使用dynamic_cast,您的基类必须至少包含一个虚函数.