c 对象数据成员存储问题

[复制链接]
查看11 | 回复0 | 2011-3-16 06:35:57 | 显示全部楼层 |阅读模式
#include iostream

using namespace std;



/*没有任何数据成员的对象类占用一个字节的空间*/

class A1

{

};



/*静态数据成员不占用类对象的存储空间*/

class A2

{


char c1;


static int count;

};



/*当只有char类型时,以1个字节为单位对齐*/

class B1

{


char c1;


char c2;

};



/*与A比较发现,当最大为short时,以2个字节为单位对齐*/

class B2

{


char c1;


short s;

};



/*与A比较发现,当最大为int时,以4个字节为单位对齐*/

class B3

{


char c1;


int i;

};



/*与A比较发现,当最大为double时,以8个字节为单位对齐*/

class B4

{


char c1;


float d;

};



/*与A比较发现,当最大为double时,以8个字节为单位对齐*/

class B5

{


char c1;


double d;

};



/*c s i 占4个字节,d占4个字节*/

class C1

{


char c;


short s;


int i;


double d;

};



/*d占4个字节,c s i 占4个字节*/

class C2

{


double d;


char c;


short s;


int i;

};



/*c占1个字节,d从下一个4字节开始占4个字节,s i在下一个4字节中*/

class C3

{


char c;


double d;


short s;


int i;

};



/*c s 在头4个字节中,d占下四个字节,i 在最后4个字节中*/

class C4

{


char c;


short s;


double d;


int i;

};





int main()

{


cout\"size of A1 : \"sizeof(A1)endl; /*1字节*/


cout\"size of A2 : \"sizeof(A2)endl; /*1字节*/




coutendl;




cout\"size of B1 : \"sizeof(B1)endl; /*2字节*/


cout\"size of B2 : \"sizeof(B2)endl; /*4字节*/


cout\"size of B3 : \"sizeof(B3)endl; /*8字节*/


cout\"size of B4 : \"sizeof(B4)endl; /*8字节*/


cout\"size of B5 : \"sizeof(B5)endl; /*8字节*/




coutendl;




cout\"size of C1 : \"sizeof(C1)endl; /*16字节*/


cout\"size of C2 : \"sizeof(C2)endl; /*16字节*/


cout\"size of C3 : \"sizeof(C3)endl; /*24字节*/


cout\"size of C4 : \"sizeof(C4)endl; /*24字节*/




system(\"pause\");


return 0;

}
为什么顺序不一样 占的内存不一样 大家帮我详细分析下 谢谢
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行