可能的重复:
c++ 中的dynamic_cast
这两种将派生类分配给基类指针的方法有什么区别?
Derived d1;
Base *b1 = &d1
Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
Run Code Online (Sandbox Code Playgroud)
这对于您的任何一种情况都不是必需的,因为两种转换都不可能失败。从派生类到基类的强制转换始终有效并且不需要强制转换。
但是,从基类指针(或引用)到派生类指针(或引用)的转换可能会失败。如果实际实例不属于它要转换到的类,则会失败。在这种情况下,dynamic_cast合适的是:
Derived d1;
Base* b = &d1; // This cast is implicit
// But this one might fail and does require a dynamic cast
Derived* d2 = dynamic_cast<Derived*> (b); // d2 == &d1
OtherDerived d3; // Now this also derives from Base, but not from Derived
b = &d3; // This is implicit again
// This isn't actually a Derived instance now, so d3 will be NULL
Derived* d3 = dynamic_cast<Derived*> (b);
Run Code Online (Sandbox Code Playgroud)