枚举
使用#define和const创建符号常量,使用enum不仅可以创建符号常量,还能定义新的数据类型。
枚举类型的声明和定义: 1 2 3 4 5 6 7 8 9 10 11 12 13
| enum wT{ Monday, Tuseday, Wednesday, Thursday, Firday, Saturday, Sunday };
wT weekday;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <iostream> using namespace std; int main() { enum wT{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; wT weekday; weekday = Monday; weekday = Tuesday; cout << weekday << endl; int a = Wednesday; cout << a << endl;
return 0; }
|
使用细节:
- 枚举值不能做左值;
- 非枚举变量不可以赋值给枚举变量;
- 枚举变量可以赋值给非枚举变量;
结构体和联合体
1 2 3 4 5 6 7 8 9 10 11 12
| struct Student { char name[6]; int age; Score s; };
union Score { double sc; char level; };
|
存储结构与结构体数据对齐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include <string.h> #include <iostream> using namespace std;
int main() { union Score { double ds; char level; }; struct Student { char name[6]; int age; Score s; };
cout << sizeof(Score) << endl; Student s1; strcpy_s(s1.name, "lili"); s1.age = 16; s1.s.ds = 95.5; s1.s.level = 'A';
cout << sizeof(Student) << endl;
return 0; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| struct s1 { char x; int z; short y; };
sizeof(s1) = 12;
struct s2 { char x; short y; int z; };
sizeof(s2) = 8;
|
数据对齐原则--缺省对齐
- 32位CPU
- char:任何地址
- short:偶数倍地址
- int:4的整数倍
- double:8的整数倍
程序是可以修改默认编译选项的,修改结构体内存分配: 1 2 3 4 5 6 7
| Visual C++: #pragma pack(n)
g++: __attribute__(aligned(n)) __attribute__(__packed__)
|