struct_union
结构体能将不同的变量放到一个单元里
struct A {
int x;
char y;
float z;
};
1
2
3
4
5
6
2
3
4
5
6
没有名字的是匿名 结构体/共用体
struct A {
struct { // anonymous struct
int x, y;
};
char z;
};
1
2
3
4
5
6
7
2
3
4
5
6
7
bitfield 的宽度是固定的,可以保存字而不是字节
struct S1 {
int b1 : 10; // range [0, 1023]
int b2 : 10; // range [0, 1023]
int b3 : 8; // range [0, 255]
}; // sizeof(S1): 4 bytes
struct S2 {
int b1 : 10;
int : 0; // reset: force the next field
int b2 : 10; // to start at bit 32
}; // sizeof(S1): 8 bytes
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
共用体能在相同的内存位置存不同的数据类型
- 只能容纳最大的数据成员
- 数据成员的内容会被其他成员覆盖
union A {
int x;
char y;
}; // sizeof(A): 4
A a;
a.x = 1023; // bits: 00..000001111111111
a.y = 0; // bits: 00..000001100000000
cout << a.x; // print 512 + 256 = 768
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
小端模式的编码和内存中存储的顺序是相反的,y 是 x 的最后的字节

C++ 17 引入了 std::variant 表示安全的共用体
编辑 (opens new window)
上次更新: 2025/05/21, 06:42:57