钻石继承类的C ++地址

时间:2017-05-13 13:48:26

标签: c++

当我将其转换为钻石继承类结构中的其他父类类型时,有人可以解释为什么对象的地址会发生变化吗?

见这个例子:

#include <iostream>

class A{
public:
    A(){};
    virtual int a(){
        return 0;
    };
};

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

class C: virtual public A{
public:
    C(){};
};

class D: public B, public C{
public:
    D(){};
};

 int main(){

     A* a = new D();

     std::cout << "dynamic_cast<A*>: " << dynamic_cast<A*>(a) << std::endl;
     std::cout << "dynamic_cast<B*>: " << dynamic_cast<B*>(a) << std::endl;
     std::cout << "dynamic_cast<C*>: " << dynamic_cast<C*>(a) << std::endl;
     std::cout << "dynamic_cast<D*>: " << dynamic_cast<D*>(a) << std::endl;
     return 0;
 }

输出结果为:

dynamic_cast<A*>: 0x11e3c20
dynamic_cast<B*>: 0x11e3c20
dynamic_cast<C*>: 0x11e3c28
dynamic_cast<D*>: 0x11e3c20

0 个答案:

没有答案