【问题标题】:Casting to derived class from base class throws exception从基类转换为派生类会引发异常
【发布时间】:2018-09-30 18:10:11
【问题描述】:

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

【问题讨论】:

  • base 的类型为 Derived
  • 和箭头是错误的。 Base Intermediate Derived.

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


【解决方案1】:

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

作为回报,dynamic_cast 可以在操作数实际上未指向目标类型对象的子对象时抛出异常,而static_cast 则未定义。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-06-21
  • 2016-05-24
  • 2017-01-08
  • 2013-11-17
  • 2014-03-09
  • 1970-01-01
相关资源
最近更新 更多