据我了解,动态转换与静态转换的不同之处在于它对 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.
最佳答案
RTTI 信息仅适用于具有虚拟成员的类。 (假设的实现是 vtable 包含 dynamic_cast 工作所需的内容;您可以制定其他方案,但所有方案都需要对象中的类型标识符,所以为什么不使用 vptr?)
关于c++ - 为什么从类到子类的动态转换要求类是多态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2229381/