什么时候需要dynamic_cast?
可能的重复:
C++ 中的dynamic_cast
这两种将派生类分配给基类的方法有什么区别指针?
Derived d1;
Base *b1 = &d1
Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
Possible Duplicate:
dynamic_cast in c++
What is the difference between these two ways of assigning a derived class to a base class pointer?
Derived d1;
Base *b1 = &d1
Derived d2;
Base *b2 = dynamic_cast<Base*> &d2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这对于您的任何一种情况都不是必需的,因为两种转换都不可能失败。从派生类到基类的强制转换始终有效并且不需要强制转换。
但是,从基类指针(或引用)到派生类指针(或引用)的转换可能会失败。如果实际实例不属于它要转换到的类,则会失败。在这种情况下,
dynamic_cast
是合适的:It's not required for either of your cases, since both casts cannot possibly fail. Casts from derived to base classes are always valid and don't require a cast.
However, casts from base-class pointers (or references) to derived-class pointer (or references) can fail. It fails if the actual instance isn't of the class it is being cast to. In such a case,
dynamic_cast
is appropriate:在多重继承的情况下,dynamic_cast 可用于“向下转换”和“交叉转换”。
一些有效的dynamic_cast示例可以在下面的链接中找到:
http://msdn.microsoft.com/en-us/library/cby9kycs%28v=vs.71%29.aspx
但 dyanmic_cast 不应该如果经常使用,您应该尝试使用良好的设计来避免使用dynamic_cast,相反,多态性应该适合您而不是dynamic_cast。
dynamic_cast can be used for "down cast" and "cross cast" in case of multiple inheritance.
Some valid dynamic_cast example can be found in the link below:
http://msdn.microsoft.com/en-us/library/cby9kycs%28v=vs.71%29.aspx
But dyanmic_cast should not be used frequently, you should aways try to used good design to avoid using dynamic_cast, instead, polymorphism should work for u instead of dynamic_cast.
来自维基百科:
与普通的C风格类型转换不同,类型安全检查是在运行时执行的,如果类型不兼容,则会抛出异常(处理引用时)或返回空指针(处理引用时)指针)。
http://en.wikipedia.org/wiki/Dynamic_cast
From wikipedia:
Unlike an ordinary C-style typecast, a type safety check is performed at runtime, and if the types are not compatible, an exception will be thrown (when dealing with references) or a null pointer will be returned (when dealing with pointers).
http://en.wikipedia.org/wiki/Dynamic_cast
第一个是显式转换,即 static_cast。具体区别可以参考:http://www.cplusplus.com/doc/tutorial /类型转换/
First one is an explicit conversion which is a static_cast. For the difference, you can refer to : http://www.cplusplus.com/doc/tutorial/typecasting/