为什么从类到子类的动态转换需要类是多态的? [英] Why does dynamic cast from class to subclass requires the class to be polymorphic?

查看:105
本文介绍了为什么从类到子类的动态转换需要类是多态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,使动态转换与静态转换不同的是它使用RTTI,并且如果变量的动态类型(当从基础到派生的转换)不匹配时,它会失败的事实。但为什么类必须是多态的,如果我们有RTTI呢?

As I understand it, what makes dynamic cast different from a static cast is its use of RTTI, and the fact that it fails if the dynamic type of a variable- when casting from base to derived- does not fit. But why does the class have to be polymorphic for that to be done if we have the RTTI anyway?

编辑:因为有一些混淆关于使用单词多态,这里是在cplusplus.com中的条目,促使我问这个:

Since there was some confusion about the use of the word "polymorphic", here's the entry in cplusplus.com that prompted me to ask this:


dynamic_cast只能用于指针和对象的引用。其目的是确保类型转换的结果是所请求类的有效完整对象。

dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

因此,当我们将类转换为一个类时,dynamic_cast总是成功的

Therefore, dynamic_cast is always successful when we cast a class to one of its base



classes: class CBase { };
class CDerived: public CBase { };

CBase b; CBase* pb; CDerived d;
CDerived* pd;

pb = dynamic_cast<CBase*>(&d);     //ok: derived-to-base 
pd = dynamic_cast<CDerived*>(&b);  //wrong: base-to-derived 




一段代码会产生编译错误,因为除非基类是多态的,否则不允许使用dynamic_cast的基础派生转换。

http://www.cplusplus.com/doc/tutorial/typecasting /

推荐答案

如果没有继承关系,可以使用什么类型的指针?在不同类型对象的指针之间执行的唯一合法和合理的转换(忽略const转换)在同一继承层次结构中。

What sort of pointer could you use if there was no inheritance relationship? The only legal and sensible casts that can be performed between pointers to objects of different types (ignoring const casts) are within the same inheritance hierarchy.

编辑: / strong>在 dynamic_cast 的第14.2.2.2节,从D& E书中引用BS:

To quote BS from the D&E book on dynamic_cast, section 14.2.2.2:


此外,具有虚拟
函数的类通常称为
多态类,多态
类是唯一可以通过
安全操作的类a base class
...从编程的角度来看,
因此似乎很自然地为多态类型提供
RTTI。

Further, a class with virtual functions is often called a polymorphic class and polymorphic classes are the only ones that can be safely manipulated via a base class ... From a programming point of view, it therefore seems natural to provide RTTI for polymorphic types only.

我强调。

这篇关于为什么从类到子类的动态转换需要类是多态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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