C++ 中 union 一种特殊的数据结构,允许在同一内存位置存储不同的数据类型。一个 union 可以有多个数据成员,但是在任意时刻只有一个数据成员可以有值。当某个成员被赋值后其他成员变为未定义状态。
union的特点
- 成员默认为 public。
- 可以有构造函数和析构函数。
- 不能包含引用类型的成员。
- 不能作为基类,也不能含有虚函数。
- 匿名联合体不能有成员函数,不能有静态数据成员,且所有数据成员必须为公开。
- 全局匿名联合最好声明为static,避免命名空间的污染和潜在的命名冲突。
union的作用
- 节省内存:由于
union
的所有成员都共享相同的内存位置,因此只占用最大成员所需的内存空间。 - 数据重用:可以在不同的时间点使用
union
来存储不同类型的数据,适用于需要根据不同情况存储不同类型数据的场景。 - 位域操作:
union
可以用于位域操作,允许程序员直接操作内存中的位。
使用示例:
下面代码展示了如何使用union
来实现一个简单的数据类型转换器,它可以存储整数或浮点数,并根据需要进行转换:
#include <iostream>
#include <string>
// 定义一个联合体,可以存储整数或浮点数
union Number {
int intValue;
float floatValue;
};
int main() {
Number num;
std::string type;
std::cout << "Enter the type of number (int/float): ";
std::cin >> type;
if (type == "int") {
std::cout << "Enter an integer: ";
num.intValue = 0;
std::cin >> num.intValue;
std::cout << "You entered the integer: " << num.intValue << std::endl;
} else if (type == "float") {
std::cout << "Enter a float: ";
num.floatValue = 0.0f;
std::cin >> num.floatValue;
std::cout << "You entered the float: " << num.floatValue << std::endl;
} else {
std::cout << "Invalid type entered." << std::endl;
}
// 演示联合体的特性:改变一个值会影响另一个
if (type == "int") {
std::cout << "Changing the integer to 123" << std::endl;
num.intValue = 123;
std::cout << "Now the float value is: " << num.floatValue << std::endl;
} else if (type == "float") {
std::cout << "Changing the float to 123.456" << std::endl;
num.floatValue = 123.456f;
std::cout << "Now the integer value is: " << num.intValue << std::endl;
}
return 0;
}