突然想到sizeof的計算,於是寫程序計算了一下,環境是32位的Ubuntu 12.04,編譯器為g++。
計算sizeof的規則大致如下:
好了,話不多說,大家看代碼就一目了然了。代碼如下:
#include<iostream>
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"<<sizeof(int)<<endl;
cout<<"sizeof(double):\t"<<sizeof(double)<<endl;
cout<<"sizeof(char):\t"<<sizeof(char)<<endl;
cout<<"sizeof(float):\t"<<sizeof(float)<<endl;
cout<<"sizeof(short):\t"<<sizeof(short)<<endl;
cout<<"sizeof(unsigned int):\t"<<sizeof(unsigned int)<<endl<<endl;
cout<<"sizeof(int *):\t"<<sizeof(int *)<<endl;
cout<<"sizeof(double *):\t"<<sizeof(double *)<<endl<<endl;
cout<<"sizeof(S1):\t"<<sizeof(S1)<<endl;
cout<<"sizeof(S2):\t"<<sizeof(S2)<<endl;
cout<<"sizeof(S3):\t"<<sizeof(S3)<<endl;
cout<<"sizeof(S4):\t"<<sizeof(S4)<<endl;
cout<<"sizeof(C1):\t"<<sizeof(C1)<<endl;
cout<<"sizeof(C2):\t"<<sizeof(C2)<<endl;
cout<<"sizeof(C3):\t"<<sizeof(C3)<<endl;
cout<<"sizeof(C4):\t"<<sizeof(C4)<<endl;
cout<<"sizeof(C5):\t"<<sizeof(C5)<<endl;
cout<<"sizeof(C6):\t"<<sizeof(C6)<<endl;
cout<<"sizeof(C7):\t"<<sizeof(C7)<<endl;
cout<<"sizeof(C8):\t"<<sizeof(C8)<<endl;
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