这是打印不同类大小的代码
#include <iostream>
using namespace std;
class EmptyClass
{
};
class AbstractClass
{
public:
virtual void funcOne() = 0;
virtual void funcTwo() = 0;
};
class NotAbstrClass
{
public: int virtFunc( int );
};
class MixClass
{
public:
virtual void clFunc( int );
static int i;
int j;
};
int main()
{
// Print size of class or class objects
cout<<"Size of empty class: "<< sizeof(EmptyClass)<<endl;
cout<<"Size of Abstract class :"<< sizeof(AbstractClass)<<endl;
cout<<"Size of Non Abstract class: "<< sizeof(NotAbstrClass)<<endl;
cout<<"Size of Mix class: "<< sizeof(MixClass)<<endl;
return 0;
}
程序在 C++11 编译器上的输出是
Size of empty class: 1
Size of Abstract class :4
Size of Non Abstract class: 1
Size of Mix class: 8
我明白为什么 Empty 类的大小为 1 Size of empty class object。对于抽象类,对象存储了一个用于实现虚函数调用机制的指针。但是其他类对象(NotAbstrClass 和 MixClass)的大小呢?