dynamic_cast< D *>(pb)返回null [英] dynamic_cast<D *>(pb) return null
问题描述
在C ++入门(第5版)19.2.1中,关于dynamic_cast.它说,要使 dynamic_cast< type *>(e)
成功,
In C++ primer(5th) 19.2.1 about dynamic_cast. It says, for dynamic_cast<type*>(e)
to be successful,
e的类型必须是从以下对象公开派生的类类型目标类型,目标类型的公共基类或与目标相同输入
但是,对于以下代码:
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类型的公共基类.
The output is "err". But the type of pb is a public base class of type D.
这是C ++入门(第5个)中的错误吗?还是我只是误解了这些话?
Is this a mistake in C++ primer(5th)? Or do I just misunderstand these words?
推荐答案
pb
的类型确实是 D
的公共基类,但 P
的对象> pb 指向的 not 不是 D
类型的任何对象的基础子对象.动态类型转换会检测到此情况并返回null.
The type of pb
is indeed a public base class of D
, but the object that pb
points to is not the base subobject of any object of type D
. The dynamic cast detects this and returns null.
如果确实确实尝试将指针转换为 D
对象的基础子对象,则将获得(非空)指向 D
对象的指针:
If indeed you did attempt to cast the pointer to a base subobject of a D
object, you would get the (non-null) pointer to the D
object:
D obj;
B *pb = &obj; // points at subobject
assert(&obj == dynamic_cast<D*>(pb));
您引用的要求仅仅是一个静态要求,它允许您完全使用动态强制转换-但是它没有描述使用强制转换的结果.稍后将对此进行描述.
The requirement that you've cited is merely a static requirement that allows you to use the dynamic cast at all -- but it does not describe the result of using the cast. That's described later on.
这篇关于dynamic_cast< D *>(pb)返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!