4

可能重复:
c++ 中的 dynamic_cast

这两种将派生类分配给基类指针的方法有什么区别?

Derived d1;
Base *b1 = &d1 

Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
4

4 回答 4

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); 
于 2011-07-28T10:23:30.307 回答
3

在多重继承的情况下,dynamic_cast 可用于“向下转换”和“交叉转换”。

可以在下面的链接中找到一些有效的 dynamic_cast 示例:

http://msdn.microsoft.com/en-us/library/cby9kycs%28v=vs.71%29.aspx

但是 dyanmic_cast 不应该经常使用,你应该尽量使用好的设计来避免使用 dynamic_cast,相反,多态应该适用于 u 而不是 dynamic_cast。

于 2011-07-28T10:26:45.737 回答
1

来自维基百科:

与普通的 C 风格类型转换不同,类型安全检查是在运行时执行的,如果类型不兼容,则会抛出异常(处理引用时)或返回空指针(处理指针时)。

http://en.wikipedia.org/wiki/Dynamic_cast

于 2011-07-28T10:11:08.027 回答
1

第一个是显式转换,它是 static_cast。区别可以参考:http ://www.cplusplus.com/doc/tutorial/typecasting/

于 2011-07-28T10:15:03.720 回答