所占字节数即为sizeof()函数的输出值。
类型 | 16位编译器 | 32位编译器 | 64位编译器 | 备注 |
---|---|---|---|---|
void | 0 | 0 | 0 | |
bool | 1 | 1 | 1 | |
char | 1 | 1 | 1 | |
short | 2 | 2 | 2 | |
int | 2 | 4 | 4 | |
long | 4 | 4 | 8 | |
float | 4 | 4 | 4 | |
double | 8 | 8 | 8 | |
enum | 2 | 4 | 4 | enum的变量其实质是整型 |
指针 | 2 | 4 | 8 | 指针存的是地址,所占字节数和编译器位数有关 |
class | x | x | x | 与具体成员类型有关,最后需对齐 |
struct | x | x | x | 与具体成员类型有关,为所有成员的和,最后再对齐 |
union | x | x | x | 以最大存储量的成员为准,最后需对齐 |
查询代码
#include<iostream>
using namespace std;
int main()
{
char str[] = "welcome to my blog";
cout << "bool:\t " << sizeof(bool) << endl;
cout << "char: \t" << sizeof(char) << endl;
cout << "string: \t" << sizeof(str) << endl;
cout << "short: " << sizeof(short) << endl;
cout << "int: " << sizeof(int) << endl;
cout << "long: " << sizeof(long) << endl;
cout << "float: " << sizeof(float) << endl;
cout << "double: " << sizeof(double) << endl;
cout << "long double: " << sizeof(long double) << endl;
cout << "bool*: " << sizeof(bool*) << endl;
cout << "char*: " << sizeof(char*) << endl;
cout << "short*: " << sizeof(short*) << endl;
cout << "int*: " << sizeof(int*) << endl;
cout << "long*: " << sizeof(long*) << endl;
cout << "float*: " << sizeof(float*) << endl;
cout << "double*: " << sizeof(double*) << endl;
cout << "long double*: " << sizeof(long double*) << endl;
enum color {red,green=0,blue,black,yellow,white};
color color1;
cout <<"枚举名称"<< sizeof(color)<<endl;
cout << "枚举变量"<<sizeof(color1)<<endl;
int array[5];
cout << "数组" << sizeof(array)<<endl;
class CGoods{
public:
//char name[33];
int amount;
//float totalvalue;
//double price;
//float a;
//double b;
void redister(char[], int, float);
int getamount();
};
CGoods good1; //所占总字节数 是 最大字节数的整数倍
cout << "类名称" << sizeof(CGoods) << endl;
cout << "类变量" << sizeof(good1) << endl;
return 0;
}