c++ - 为什么 dynamic_cast 可以用于非多态类型的向上转换?

标签 c++ pointers polymorphism dynamic-cast

参见 here :

dynamic_cast can only be used with pointers and references to classes (or with void*). Its purpose is to ensure that the result of the type conversion points to a valid complete object of the destination pointer type.

This naturally includes pointer upcast (converting from pointer-to-derived to pointer-to-base), in the same way as allowed as an implicit conversion.

But dynamic_cast can also downcast (convert from pointer-to-base to pointer-to-derived) polymorphic classes (those with virtual members) if -and only if- the pointed object is a valid complete object of the target type.

为什么 dynamic_cast 可以用于非多态类型的向上转换,但不能用于非多态类型的向下转换?

最佳答案

将派生类型指针转换为基类型指针可以在不知道所指向对象的确切类型的情况下完成,因为派生类型始终是基类型的实例类型。也就是说,转换仅取决于静态 信息。所以 dynamic_cast 在那个方向上总是没问题的,因为它总是可以完成的。

使用 dynamic_cast 转换另一种方式需要知道所指向对象的实际类型,因为没有该信息就无法知道转换是否有效。例如:

Base* bp = get_base();
Derived* dp = dynamic_cast<Derived*>(bp);

在这种情况下,如果 bp 实际上指向类型为 Base 的对象,则转换无效;如果它指向 Derived 类型的对象或从 Derived 派生的类型,则转换没问题。

为了在运行时确定对象的确切类型,支持代码依赖于嵌入的类型信息,该信息只需要存在于多态类型中。这就是为什么从基础到派生的转换需要多态类型:它确保存在所需的信息。

诚然,该标准本可以使派生到基础的转换对于非多态类型无效,但这是一个 procrustean 限制;没有充分的理由禁止它。

关于c++ - 为什么 dynamic_cast 可以用于非多态类型的向上转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38954826/

相关文章:

c++ - 使用指向类 T 成员的函数指针作为模板类 <T> 函数中的参数的不良做法?

c - 保存指针的内存地址

c - 我的指针和动态分配的实现是否正确?

Java OOP多态设计/问题

delphi - 如何在兼容的方法指针之间进行转换?

c++ - 从头开始进行多目录项目的 Cmake

c++ - 跳过 unordered_map 的第一次迭代

c++ - 链接到 boost::program_options 不能正常工作

c - 如何释放结构数组中的指针

java - 如何从 Java 代码生成 Go 代码?