gpt4 book ai didi

c++ - 从基类转换到派生类抛出异常

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:01 26 4
gpt4 key购买 nike

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

最佳答案

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

作为返回,如果操作数实际上并未指向目标类型对象的子对象,则 dynamic_cast 会抛出异常,而 static_cast 则未定义。

关于c++ - 从基类转换到派生类抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49934628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com