gpt4 book ai didi

c++ - dynamic_cast(pb) 返回 null

转载 作者:搜寻专家 更新时间:2023-10-31 00:08:45 24 4
gpt4 key购买 nike

在 C++ primer(5th) 19.2.1 中关于 dynamic_cast。它说,对于 dynamic_cast<type*>(e)想要成功,

the type of e must be either a class type that is publicly derived from the target type, a public base class of the target type, or the same as the target type

但是,对于下面的代码:

class B{
public:
virtual ~B(){}
};

class D : public B{};

B *pb = new B;
D *pd = dynamic_cast<D*>(pb);
if(pd == 0) cout << "err" << endl;

输出是“err”。但是 pb 的类型是类型 D 的公共(public)基类。

这是 C++ primer(5th) 中的错误吗?还是我只是误解了这些词?

最佳答案

pb的类型确实是D的公共(public)基类,但是pb指向的对象不是 D 类型的任何对象的基本子对象。动态转换检测到这一点并返回 null。

如果您确实尝试将指针转换为 D 对象的基础子对象,您将获得指向 D 对象的(非空)指针:

D obj;
B *pb = &obj; // points at subobject

assert(&obj == dynamic_cast<D*>(pb));

您引用的要求仅仅是允许您使用动态转换的静态要求——但它没有描述使用转换的结果。这在后面描述。

关于c++ - dynamic_cast<D *>(pb) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47172507/

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