C++ 中 struct 和 union 的区别及使用
struct 与 union 的区别
-
内存分配方式:
struct:每个成员拥有独立的内存空间,结构体大小为所有成员大小之和(考虑对齐)union:所有成员共享同一块内存空间,联合体大小为最大成员的大小
-
存储特性:
struct:可以同时存储所有成员的值union:同一时间只能存储一个成员的值,赋值新成员会覆盖旧成员
-
访问方式:
- 两者都使用点运算符(.)访问成员
-
初始化:
struct:可以初始化所有成员union:通常只初始化第一个成员
union 的使用优化示例
1. 节省内存空间
// 用于表示不同数据类型的值
union Value {
int i;
float f;
char c;
double d;
};
int main() {
Value v;
v.i = 42; // 存储整型
cout << v.i; // 输出: 42
v.f = 3.14f; // 现在存储浮点数,之前的整型值被覆盖
cout << v.f; // 输出: 3.14
// sizeof(Value) == sizeof(double) (假设double是最大的类型)
return 0;
}
2. 类型转换技巧
union FloatInt {
float f;
int i;
};
void printFloatBits(float num) {
FloatInt fi;
fi.f = num;
// 以二进制形式打印float的内部表示
for(int i = 31; i >= 0; i--) {
cout << ((fi.i >> i) & 1);
if(i % 8 == 0) cout << " ";
}
cout << endl;
}
3. 协议解析优化
// 网络协议中的IP地址处理
union IPAddress {
uint32_t address; // 作为32位整型
uint8_t octets[4]; // 作为4个字节
};
void printIP(IPAddress ip) {
// 两种方式访问相同的数据
cout << "整型表示: " << ip.address << endl;
cout << "点分十进制: "
<< (int)ip.octets[0] << "."
<< (int)ip.octets[1] << "."
<< (int)ip.octets[2] << "."
<< (int)ip.octets[3] << endl;
}
4. 变体记录实现
// 表示不同类型的形状
struct Circle { float radius; };
struct Rectangle { float width, height; };
union ShapeData {
Circle circle;
Rectangle rect;
};
enum class ShapeType { CIRCLE, RECTANGLE };
struct Shape {
ShapeType type;
ShapeData data;
};
float calculateArea(const Shape& shape) {
switch(shape.type) {
case ShapeType::CIRCLE:
return 3.14159f * shape.data.circle.radius * shape.data.circle.radius;
case ShapeType::RECTANGLE:
return shape.data.rect.width * shape.data.rect.height;
}
return 0.0f;
}
注意事项
- 安全性:访问非当前活跃的成员是未定义行为,可能导致程序崩溃或数据错误
- C++17改进:引入了
std::variant作为更安全的替代方案 - 构造函数限制:union不能包含有非平凡构造函数的成员(C++11后放宽了部分限制)
- 用途:union最适合用于需要节省内存且明确知道当前存储类型的场景
在C++中,union的这些特性使其特别适合底层编程、协议解析、硬件寄存器映射等需要精确控制内存布局的场景。
2万+




被折叠的 条评论
为什么被折叠?



