我们都知道,当使用简单的单继承时,派生类的地址与基类的地址相同。多重继承使这不成立。
虚拟继承是否也使这不成立?换句话说,以下代码是否正确:
struct A {};
struct B : virtual A
{
int i;
};
int main()
{
A* a = new B; // implicit upcast
B* b = reinterpret_cast<B*>(a); // fishy?
b->i = 0;
return 0;
}
最佳答案
We all know that when using simple single inheritance, the address of a derived class is the same as the address of the base class.
我认为这一说法是不正确的。在下面的代码中,我们有一个简单的(非虚拟的)单(非多重)继承,但是地址是不同的。
class A
{
public:
int getX()
{
return 0;
}
};
class B : public A
{
public:
virtual int getY()
{
return 0;
}
};
int main()
{
B b;
B* pB = &b;
//A* pA = dynamic_cast<A*>(pB);
A* pA = static_cast<A*>(pB);
std::cout << "The address of pA is: " << pA << std::endl;
std::cout << "The address of pB is: " << pB << std::endl;
return 0;
}
VS2015的输出为:
The address of pA is: 006FF8F0
The address of pB is: 006FF8EC
Does virtual inheritance also make that untrue?
如果将上述代码中的继承更改为virtual,则结果将相同。因此,即使在虚拟继承的情况下,基础对象和派生对象的地址也可以不同。
关于c++ - 子类地址等于虚拟基类地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60202939/