#ifndef _TEST_H
#define _TEST_H
#include <iostream>
#include <string>
using namespace std;
//这三种数据类型使用方式相似,都是使用成员对象操作符对成员进行操作。
//如:test_struct ts; ts.f=10;
//test_enum te; te=RED
//test_union tu; tu.ch="hello"
struct test_struct
{
short int c;
int f;
char ch[17];//这个字节对齐的时候是按照char的长度进行对齐
};
enum test_enum
{
RED,
BLUE,
GREEN,
};
//节省空间,所有成员都是公用一个起始地址
union test_union
{
test_union(){};
char a;
int b;
double c;
short int d;
char ch[100];
};
void main()
{
//注意:数据类型都是说几个机器字长,如int是一个机器字长,如果在32
//位(x86)的机器上就是4个字节,而在64位(x86_64)的机器上就是4字节
//其他的数据也是如此
cout << sizeof(int) << endl;
cout << sizeof(double) << endl;
cout << sizeof(long) << endl;
cout << sizeof(long long) << endl;
cout << sizeof(char [10]) << endl;
cout << sizeof(int &) << endl;
cout << sizeof(double &) << endl;
//注意c++的字节对齐方式
cout << sizeof(test_struct) << endl;
cout << sizeof(test_enum) << endl;
//注意,这里虽然没有求和,但是也涉及到了计算数据类型边界时候也是字节对齐最大数据类型
cout << sizeof(test_union) << endl;
}
#endif //_TEST_H
c++一些数据结构占用空间大小的判断
最新推荐文章于 2024-01-15 10:27:30 发布