我有3个继承类:Base
- > Intermediate
- > Derived
。
为什么在我使用dynamic_cast
时会抛出异常?
class Base { ... };
class Intermediate : public Base { ... };
class Derived : public Intermediate { ... };
Base* base = new Derived();
// No throw
auto intermediate = static_cast<Intermediate *>(base);
auto derived1 = static_cast<Derived *>(base);
auto derived2 = static_cast<Derived *>(intermediate);
// All throw
// (vcruntime140d.dll): Access violation reading location [...].
auto intermediate = dynamic_cast<Intermediate *>(base);
auto derived1 = dynamic_cast<Derived *>(base);
auto derived2 = dynamic_cast<Derived *>(intermediate);
答案 0 :(得分:0)
当转换为指向派生类的指针时,dynamic_cast
的操作数应该是指向多态类型的指针,这是一个声明或继承虚函数的类,而static_cast
没有此约束。
作为回报,如果操作数实际上没有指向目标类型对象的子对象,dynamic_cast
可以抛出异常,而static_cast
使其未定义。