从基类转换为派生类会引发异常

时间:2018-04-20 05:31:32

标签: c++ inheritance casting dynamic-cast static-cast

我有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);

1 个答案:

答案 0 :(得分:0)

当转换为指向派生类的指针时,dynamic_cast的操作数应该是指向多态类型的指针,这是一个声明或继承虚函数的类,而static_cast没有此约束。

作为回报,如果操作数实际上没有指向目标类型对象的子对象,dynamic_cast可以抛出异常,而static_cast使其未定义。