当我将其转换为钻石继承类结构中的其他父类类型时,有人可以解释为什么对象的地址会发生变化吗?
见这个例子:
#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