记住几句话:
结构体的长度一定是最长的数据元素类型的整数倍;
某数据元素的起始地址能被该类型所占的字节数整除;
静态变量是存放在全局数据区,而sizeof计算栈中分配的大小,不包括static变量;
#include <iostream> #include <stdio.h> using namespace std; struct{//6 short a1; short a2; short a3; }A; struct{//8 char c1; char c2; short s; int i; }B; struct{//12 char c1; short s; char c2; int i; }C; class D{//4 public: int b; static char c; }; struct{//22!!(总大小是2的倍数) char d; short b[8]; char a[3]; }E; struct{//32!! char a[10]; int b; char c; double d;//(起始地址是8的倍数) }F; class G{//24!!(总大小是8的倍数) public: double d; float a; int b; char c; G(); ~G(); }; int main(){ cout<<sizeof(A)<<" "; cout<<sizeof(B)<<" "; cout<<sizeof(C)<<" "; cout<<sizeof(D)<<" "; cout<<sizeof(E)<<" "; cout<<sizeof(F)<<" "; cout<<sizeof(G)<<" "; return 0; }
运行结果: