之前被问到空类的大小,今天就做了个测试,来验证一下空类的大小,测试代码如下
#include <iostream>
using namespace std;
class empty
{
};
class child1 : public empty
{
};
class child2 : public empty
{
private:
int a;
};
int main(int argc, char const *argv[])
{
empty myEmpty;
child1 myChild1;
child2 myChild2;
cout << "empty class size : " << sizeof(myEmpty) << endl;
cout << "child1 size: " << sizeof(myChild1) << endl;
cout << "child2 size: " << sizeof(myChild2) << endl;
return 0;
}
程序执行的打印如下:
empty class size : 1
child1 size: 1
child2 size: 4
由这个结果可以分析出来,对于空类,C++不允许大小为0,故把类的大小设为了1。
子类继承空类的结果分为两种:
- 如果子类也是空类,那么子类的大小同样也是1,不会因为继承关系而加个1变成2。
- 如果子类不是空类,子类就有了大小,就不需要增加1,所以子类的大小就是成员变量的大小。