为什么基本派生的动态强制转换只允许用于多态类 [英] Why Base-to-Derived Dynamic Casting is Only Allowed for Polymorphic Classes

查看:139
本文介绍了为什么基本派生的动态强制转换只允许用于多态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

常见问题:为什么只有当一个类至少有一个虚方法时dynamic_cast才起作用? p>

Possible Duplicate:
FAQ: Why does dynamic_cast only work if a class has at least 1 virtual method?

我在C ++中读过,在一组类的层次结构中执行动态转换, cast只允许在类是多态的情况下,例如当基类有一个虚函数等时。这个限制的原因是什么?在基类中有一个纯虚函数代替普通的虚函数更安全吗?

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?

谢谢!

推荐答案


此限制的原因是什么?

What is the reason for this limitation?

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.


使用纯虚拟函数代替普通虚拟函数更安全基类?

Is it more 'safe' to have a pure virtual function in place of the normal virtual function in the base class?

就多态性而言,这很好。如果基类有至少一个虚函数,那么它是多态的,因此可以使用 dynamic_cast 。无论是纯还是不影响基类是否可以实例化。

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.

这篇关于为什么基本派生的动态强制转换只允许用于多态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆