可能重复:
dynamic_cast in c++
这两种将派生类分配给基类指针的方法有什么区别?
Derived d1;
Base *b1 = &d1
Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
答案 0 :(得分:4)
这两种情况都不需要,因为两个演员阵容都不可能失败。从派生类到基类的强制转换始终有效,不需要强制转换。
但是,从基类指针(或引用)到派生类指针(或引用)的强制转换可能会失败。如果实际实例不属于要转换的类,则它会失败。在这种情况下,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);
答案 1 :(得分:3)
dynamic_cast可用于“向下投射”和“交叉投射”。
可以在以下链接中找到一些有效的dynamic_cast示例:
http://msdn.microsoft.com/en-us/library/cby9kycs%28v=vs.71%29.aspx
但是dyanmic_cast不应该经常使用,你应该尝试使用好的设计来避免使用dynamic_cast,相反,多态应该适用于你而不是dynamic_cast。
答案 2 :(得分:1)
来自维基百科:
与普通的C风格类型转换不同,在运行时执行类型安全检查,如果类型不兼容,则抛出异常(处理引用时)或返回空指针(处理时)指针)。
答案 3 :(得分:1)
第一个是显式转换,即static_cast。有区别,您可以参考:http://www.cplusplus.com/doc/tutorial/typecasting/