C++中sizeof如何计算类和struct的大小

2014-11-24 09:07:25 · 作者: · 浏览: 1

计算sizeof的规则大致如下:


好了,话不多说,大家看代码就一目了然了。代码如下:


#include
using namespace std;
struct S1
{
};
struct S2
{
int a;
char b;
double c;
};
struct S3
{
double a;
int b;
char c;
};
struct S4
{
char a;
double b;
int c;
};
class C1
{
};
class C2
{
char a;
int b;
double c;
};
class C3
{
double a;
char b;
int c;
};
class C4:C1
{
int a;
};
class C5:C1
{
virtual void a();
};
class C6:C5
{
int c;
};
class C7:C5
{
virtual void a();
};
class C8:C5
{
virtual void a();
double b;
int c;
};


int main(int argc,char *argv[])
{
cout<<"sizeof(int):\t"< cout<<"sizeof(double):\t"< cout<<"sizeof(char):\t"< cout<<"sizeof(float):\t"< cout<<"sizeof(short):\t"< cout<<"sizeof(unsigned int):\t"<

cout<<"sizeof(int *):\t"< cout<<"sizeof(double *):\t"<

cout<<"sizeof(S1):\t"< cout<<"sizeof(S2):\t"< cout<<"sizeof(S3):\t"< cout<<"sizeof(S4):\t"< cout<<"sizeof(C1):\t"< cout<<"sizeof(C2):\t"< cout<<"sizeof(C3):\t"< cout<<"sizeof(C4):\t"< cout<<"sizeof(C5):\t"< cout<<"sizeof(C6):\t"< cout<<"sizeof(C7):\t"< cout<<"sizeof(C8):\t"< return 0;
}


运行结果如下:


sizeof(int): 4
sizeof(double): 8
sizeof(char): 1
sizeof(float): 4
sizeof(short): 2
sizeof(unsigned int): 4


sizeof(int *): 4
sizeof(double *): 4


sizeof(S1): 1
sizeof(S2): 16
sizeof(S3): 16
sizeof(S4): 16
sizeof(C1): 1
sizeof(C2): 16
sizeof(C3): 16
sizeof(C4): 4
sizeof(C5): 4
sizeof(C6): 8
sizeof(C7): 4
sizeof(C8): 16