类字节大小,字节对齐相关

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值