这是我的代码:
#include <iostream>
using namespace std;
class MyClass{
int mem1;
float mem2;
};
class MyKids: public virtual MyClass{
int cmem1;
int cmem2;
};
class MyLawKids:public virtual MyClass{
int lmem1;
};
class MyGrands:public MyKids, public MyLawKids{
int gmem1;
};
int main(){
cout << "\n Size of MyClass: " << sizeof(MyClass) << " bytes" << endl ;
cout << " Size of MyKids: " << sizeof(MyKids) << " bytes" << endl ;
cout << " Size of MyLawKids: " << sizeof(MyLawKids) << " bytes" << endl ;
cout << " Size of MyGrands: " << sizeof(MyGrands) << " bytes" << endl ;
return 0;
}
结果:
Size of MyClass: 8 bytes
Size of MyKids: 20 bytes
Size of MyLawKids: 16 bytes
Size of MyGrands: 32 bytes
Process returned 0 (0x0) execution time : 0.094 s
Press any key to continue.
我认为MyGrands类的大小应该是36个字节=(sizeof(MyKids + MyLawKids + int gmem1) - 4个字节的虚拟表指针)。
为什么我的结果显示“MyGrands的大小:32字节”?
答案 0 :(得分:2)
MyGrands
仅包含来自MyClass
的{{1}}和来自MyKids
的{{1}} inheriting virtually的MyLawKids
个实例。因此,通过重复计算MyClass
的大小,您的计算是错误的。顺便说一句,一般来说,你不应该依赖天真地添加与整体大小相同的碎片。编译器可以添加填充。