简体   繁体   English

关于动态铸件和(钻石)inheritance

[英]About dynamic cast and (diamond) inheritance

I have the following code snipped:我剪掉了以下代码:

#include <iostream>
#include <typeinfo>
using namespace std;


class B{
int i;
public:
    B(){i = 1;}

virtual int get_i(){return i;}

};

class D: virtual public B{
    int j;
public:
    D(){j = 2;}
    int get_i(){return B::get_i() + j;}
};

class D2: virtual public B{
    int j2;
public:
    int get_i(){return B::get_i() + j2;}
};


class MM: public D, public  D2{
    int x;
public:
    MM(){
        x = D::get_i() + D2::get_i();
    }
    int get_i(){return x;}
};

int main(){
    B* o = new MM();
    cout << o->get_i() << "\n";
    MM* p = dynamic_cast<MM*>(o);
    if(p) cout << p->get_i() << "\n";
    D* p2 = dynamic_cast<D*>(o); /// Why does this dynamic_cast not return NULL?
    if(p2)
        cout << p2->get_i() << "\n";
}

The output will be:

My question is: Why does the dynamic_cast on the marked line success?我的问题是:为什么标记线上的 dynamic_cast 成功了? So, if I have an hierarchy like:所以,如果我有这样的层次结构:

class Grandpa{...};
class Dad : public Grandpa{...};
class Son: public Dad{...};

Of course that当然那

Grandpa* grandpa = new Son();

Is ok.没关系。

Will the following dynamic_cast :将以下dynamic_cast

Dad* dad = dynamic_cast<Dad*>(grandpa);

always succeed?总是成功?

It's somehow logical, as long as a Dad pointer always can point to a Son object, but I have never seen this before, and I want to assure that I can take that as a general rule.这在某种程度上是合乎逻辑的,只要Dad指针总是可以指向Son object,但我以前从未见过这种情况,我想保证我可以将其作为一般规则。

Why does the dynamic_cast on the marked line success?为什么标记线上的dynamic_cast会成功?

Because the dynamic type of the object has a D base.因为 object 的动态类型有一个D基。

Will the following dynamic_cast:将以下dynamic_cast:

 Dad* dad = dynamic_cast<Dad*>(grandpa);

always succeed?总是成功?

Given the premise of Grandpa* grandpa = new Son();假设Grandpa* grandpa = new Son(); , yes it will succeed. ,是的,它会成功。

But it won't succeed in other cases such as for example:但在其他情况下它不会成功,例如:

Grandpa gp;
Grandpa* grandpa = &gp;
Dad* dad = dynamic_cast<Dad*>(grandpa); // is null

Yes, as long as the object pointed to by the superclass-type pointer really is an object of the type you are trying to cast to, dynamic_cast will succeed.是的,只要超类类型指针指向的 object 确实是您尝试转换的类型的 object,dynamic_cast 就会成功。 If it isn't an object of that type, otoh, dynamic_cast will return a null pointer.如果它不是该类型的 object,otoh,dynamic_cast 将返回 null 指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM