为什么仅允许多态类进行从基到派生的动态转换
我读过,在C++中,在一组类的层次结构中执行动态强制转换,仅在以下情况下才允许强制转换:类是多态的,例如当基类具有虚函数时等。这种限制的原因是什么?使用纯虚函数代替基类中的普通虚函数是否更“安全”?
谢谢你!
Possible Duplicate:
FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?
I have read that in C++, performing a dynamic cast down the hierarchy of a set of classes, the cast is allowed only in a situation where the classes are polymorphic, such as when the base class is having a virtual function, etc. What is the reason for this limitation? Is it more 'safe' to have a pure virtual function in place of the normal virtual function in the base class?
Thank You!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当对象是目标类型的实例时,
dynamic_cast
才应该成功。非多态类不包含任何类型信息,因此无法判断是否是这种情况;因此,演员阵容无法成功。
就多态性而言,两者都可以。如果基类至少有一个虚函数,那么它是多态的,因此可以与
dynamic_cast
一起使用。是否纯仅影响基类能否被实例化。dynamic_cast
is only supposed to succeed when the object is an instance of the target type.Non-polymorphic classes don't contain any type information, so there is no way to tell whether this is the case; therefore, the cast cannot succeed.
Either is fine, as far as polymorphism is concerned. If the base class has at least one virtual function, then it is polymorphic, and so can be used with
dynamic_cast
. Whether it's pure or not only affects whether the base class can be instantiated.这是标准引起的限制。
在主要实现中,
dynamic_cast
通过比较两个类的vfptr
(虚拟函数表指针)来工作。这是确定类在运行时是否相关的一种方法。此外,对非多态类进行
dynamic_cast
并没有真正的意义。有static_cast
来实现这一点。我的猜测是,如果您尝试在非多态类上使用
dynamic_cast
,您就做错了。如果您发布一些代码,我们可以提供帮助。It's a limitation induced by the standard.
In major implementations,
dynamic_cast
works by comparing thevfptr
- virtual function table pointer - of two classes.That's one way to determine whether classes are related at run-time. Besides, it wouldn't really make sense to do a
dynamic_cast
on non-polymorphic classes. There'sstatic_cast
for that.My guess is that you're doing something wrong, if you're trying to use
dynamic_cast
on non-polymorphic classes. If you post some code, we could help.执行
dynamic_cast
时,会在运行时执行类型检查,并且当强制转换非法时,会引发std::bad_cast
异常或返回空指针。允许执行此操作的机制称为 RTTI。
当类不是多态时,无法执行类型检查,因为运行时不存储类型信息。
When performing a
dynamic_cast
there is a type check performed at a runtime andstd::bad_cast
exception is thrown or null pointer is returned when the cast is illegal.The mechanism allowing to do this is called RTTI.
When class are not polymorphic there is no way to perform that typecheck, because no type information is stored at the runtime.