c++ - 为什么从类到子类的动态转换要求类是多态的?

标签 c++ casting rtti

据我了解,动态转换与静态转换的不同之处在于它对 RTTI 的使用,以及如果变量的动态类型(从基类型转换为派生类型)不适合则它会失败的事实。但是,如果我们有 RTTI,为什么类必须是多态的才能完成?

编辑:由于对“多态”一词的使用存在一些混淆,这里是 cplusplus.com 中的条目,促使我提出这个问题:

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.

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 

The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with dynamic_cast unless the base class is polymorphic.

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

最佳答案

RTTI 信息仅适用于具有虚拟成员的类。 (假设的实现是 vtable 包含 dynamic_cast 工作所需的内容;您可以制定其他方案,但所有方案都需要对象中的类型标识符,所以为什么不使用 vptr?)

关于c++ - 为什么从类到子类的动态转换要求类是多态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229381/

相关文章:

c++ - 旋转框的值,就在其更改之前

c++ - ASIO使用删除函数C++

delphi - 如何使用delphi 2010 rtti设置数组长度

c++ - 从 GCC 可执行文件中剥离符号和 RTTI 文本

delphi - 使用 RTTI 从类中获取常量字段

c++ - 预编译器会评估位移位和算术运算吗?

c++ - 不移动就不能从函数返回 std::unique_ptr

arrays - 在 swift 中将字符串转换为数组(来自 Parse 服务器)

java - 为什么这个通用转换不会失败?

c++ - 根据 C++ 中的用户输入更改模板类型