VC下的结构体和类的默认对齐原则:
1.各成员变量存放的起始地址相对于结构的起始地址偏移量必须为该变量类型所占用字节的倍数。
2.结构总大小必须为结构的字节边界数(结构中占用最大空间的类型所占字节数)的倍数。
没有成员变量的结构体或类的大小为1,因为必须保证结构或类的实例在内存中都有唯一的地址。
VC中修改默认对齐方式:
#pragma pack(push) // 保存对齐状态
#pragma pack(1) // 设定为1字节对齐
#pragma pack(pop) // 恢复对齐状态
// =======================================================
// 以下为练习
// =======================================================
#include <iostream>
using namespace std;
struct STA1
{
char c;
double d;
int n;
};
struct STB1
{
};
struct STC1
{
double d;
int n;
char c;
};
class CA1
{
char c;
double d;
int n;
};
class CB1
{
};
// ============================================================
#pragma pack( push ) // 保存对齐状态
#pragma pack( 1 ) // 设定为1字节对齐
struct STA2
{
char c;
double d;
int n;
};
struct STB2
{
};
struct STC2
{
double d;
int n;
char c;
};
class CA2
{
char c;
double d;
int n;
};
class CB2
{
};
#pragma pack( pop ) // 恢复对齐状态
// ============================================================
int main(void)
{
cout<<"sizeof(STA1) = "<<sizeof(STA1)<<endl;
cout<<"sizeof(STA2) = "<<sizeof(STA2)<<endl;
cout<<"sizeof(STB1) = "<<sizeof(STB1)<<endl;
cout<<"sizeof(STB2) = "<<sizeof(STB2)<<endl;
cout<<"sizeof(STC1) = "<<sizeof(STC1)<<endl;
cout<<"sizeof(STC2) = "<<sizeof(STC2)<<endl;
cout<<"sizeof(CA1) = "<<sizeof(CA1)<<endl;
cout<<"sizeof(CA2) = "<<sizeof(CA2)<<endl;
cout<<"sizeof(CB1) = "<<sizeof(CB1)<<endl;
cout<<"sizeof(CB2) = "<<sizeof(CB2)<<endl;
cin.get();
return 0;
}