菱形继承中类对象大小
空类大小为1
class A
{
};
int main()
{
cout << sizeof(A) << endl;
}
不做处理的情况下继承中类的大小
class A
{
protected:
int _a;
};
class B : public A
{
protected:
int _b;
};
class C : public A
{
protected:
int _C;
};
class D : public B, public C
{
protected:
int _d;
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
cout << sizeof(D) << endl;
}
D类对象大小计算
如上图所示,D中继承了两个A类中的成员,并且没有叠加,所以B中共有5个int类型成员:
所以,D类的大小为20个字节。
虚继承情况下D类的大小计算方式
class A //基类
{
protected:
int _a1 = 1;
int _a2 = 10;
};
class B : virtual public A //B继承A
{
protected:
int _b = 2;
};
class C : virtual public A //C继承A
{
protected:
int _c = 3;
};
class D : public B, public C //D继承B、C
{
protected:
int _d = 4;
};
int main()
{
cout << sizeof(A) << endl; //8
cout << sizeof(B) << endl; //16
cout << sizeof(C) << endl; //16
cout << sizeof(D) << endl; //28
}
在上一节(四)中我们得知,虚继承中类对象模型为如下所示:
可以知道,为了防止A类中的变量重复冗余,所以使用_vbptr虚基表指针访问虚基表得出偏移量的方法,来访问A类中的成员。
B类对象模型大小
所以,在这种虚继承方式下,B类的类对象模型为:
所以,得出B的大小为16字节。同理得出C。
D类对象模型大小
可以看出,D对象中包含2个指针,5个数据,并且消除了A类继承中的冗余数据。所以,D类的大小为28个字节。