可能是重复问题:
c++中的dynamic_cast
将派生类赋值给基类指针的这两种方式有什么区别?
Derived d1;
Base *b1 = &d1
Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
可能是重复问题:
c++中的dynamic_cast
将派生类赋值给基类指针的这两种方式有什么区别?
Derived d1;
Base *b1 = &d1
Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
对于这两种情况,都不需要强制类型转换,因为它们不可能失败。从派生类到基类的强制类型转换总是有效的,并且不需要进行强制类型转换。
然而,从基类指针(或引用)到派生类指针(或引用)的强制类型转换可能会失败。如果实际的实例不是要强制转换成的类,则会失败。在这种情况下,应使用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);
dynamic_cast可以用于多重继承中的“向下转换”和“交叉转换”。
以下链接中可以找到一些有效的dynamic_cast示例:
http://msdn.microsoft.com/en-us/library/cby9kycs%28v=vs.71%29.aspx
但是 dynamic_cast 不应该频繁使用,您应该始终尝试使用良好的设计来避免使用 dynamic_cast,而不是使用 dynamic_cast 来代替多态。
来自维基百科:
与普通的C风格类型转换不同,运行时会执行类型安全检查,如果类型不兼容,则会抛出异常(处理引用时)或返回空指针(处理指针时)。
第一个是显式转换,即 static_cast。关于它与其他类型转换的区别,您可以参考:http://www.cplusplus.com/doc/tutorial/typecasting/
dynamic_cast
和static_cast
视为相同。唯一会发生运行时检查(也是dynamic_cast
在运行时可能失败的唯一时间)的情况是在相反方向上进行转换,即从Base*
到派生类。 - James Kanze