1、空类为1字节,虚函数指针为4字节(字节按double对齐时为8字节),子类在父类的字节大小上面累加
class B
{
double a; //8字节
int b;
public:
virtual ~B(){ cout << "B::~B()" << endl; }
};
class D : public B
{
int i;
int j;
public:
virtual ~D() { cout << "D::~D()" << endl; }
};
int main(void)
{
cout << "sizeB:" << sizeof(B) << " sizeD:" << sizeof(D) << endl;
B *pb = new D[2];
delete[] pb;
return 0;
}
类B按8字节对齐,类D按4字节对齐,所以sizeof(B): 24 sizeof(D):32
<span style="font-family: Arial, Helvetica, sans-serif;">#pragma pack(1)</span>
在B类前面加上#pragma pack(1)时,则按1字节对齐, <span style="font-family: Arial, Helvetica, sans-serif;">所以sizeof(B): 16 sizeof(D):24