c++ 联合(Union)的特性和使用

C++ 中 union 一种特殊的数据结构,允许在同一内存位置存储不同的数据类型。一个 union 可以有多个数据成员,但是在任意时刻只有一个数据成员可以有值。当某个成员被赋值后其他成员变为未定义状态。

union的特点

  1. 成员默认为 public。
  2. 可以有构造函数和析构函数。
  3. 不能包含引用类型的成员。
  4. 不能作为基类,也不能含有虚函数。
  5. 匿名联合体不能有成员函数,不能有静态数据成员,且所有数据成员必须为公开。
  6. 全局匿名联合最好声明为static,避免命名空间的污染和潜在的命名冲突。

union的作用

  1. 节省内存:由于union的所有成员都共享相同的内存位置,因此只占用最大成员所需的内存空间。
  2. 数据重用:可以在不同的时间点使用union来存储不同类型的数据,适用于需要根据不同情况存储不同类型数据的场景。
  3. 位域操作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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值