C++学习笔记(三十八):c++ 联合体

本节介绍c++联合体union。一个联合体只能有一个成员,例如我们声明4个float变量,但联合体的大小仍为4字节,这4个float的内存是一样的。可以像结构体一样使用联合体,可以添加静态函数或者普通函数方法等。但不能使用虚函数。一般使用联合体和类型双关相关联。类型双关是指将同一块内存的数据类型转换成其他数据类型。例如将int a = 4;float b = (float),此处仅仅举例。当想给同一个变量取不同的名字是,联合体的作用就体现出来了。例如一个结构体Vector3(x,y,y),既想当作向量,又想当作三原色RGB。代码示例如下:

cpp 复制代码
#include<iostream>
struct Vector2
{
    float x,y;
};
struct Vector4
{
    float x,y,z,w;
};

void PrintVector2(const Vector2& vector)
{
    std::cout << vector.x << ", " << vector.y << std::endl;
}

int main(){
    struct TestUnion
    {
        //创建一个匿名联合体,既可以表示float又可以表示int。
        union
        {
            float a;
            int b;
        };
    };
    TestUnion u;
    u.a = 2.0f;
    std::cout<< u.a << ", " << u.b << std::endl;

    std::cin.get();
}

2, 1073741824

  • 输出的2是float型2,1073741824是float型2的二进制表示。
cpp 复制代码
#include<iostream>
struct Vector2
{
    float x,y;
};
struct Vector4
{
    //可以看做是两个Vector2
    union 
    {
        //两种访问Vector4的方式
        struct 
        {
            float x,y,z,w;
        };
        struct 
        {
            Vector2 a,b;//a对应x,y,b对应z,w
        };
        
    };
};

void PrintVector2(const Vector2& vector)
{
    std::cout << vector.x << ", " << vector.y << std::endl;
}

int main(){
    Vector4 vector = {1.0f,2.0f,3.0f,4.0f};
    PrintVector2(vector.a);
    PrintVector2(vector.b);
    vector.z = 800.0f;
    PrintVector2(vector.a);
    PrintVector2(vector.b);
    std::cin.get();
}

1, 2

3, 4

1, 2

800, 4

  • 上述示例展示如何不新增PrintVector4函数,仅通过联合体通过PrintVector2来打印Vector4。
相关推荐
好奇龙猫2 小时前
【日语学习-日语知识点小记-日本語体系構造-JLPT-N2前期阶段-第一阶段(19):単語文法】
学习
挨踢学霸6 小时前
技术全面重构|MsgHelper 新版深度拆解:交互、视觉与逻辑的底层优化(二)
经验分享·笔记·微信·架构·自动化
Nan_Shu_6146 小时前
学习: 尚硅谷Java项目之小谷充电宝(3)
java·后端·学习
头疼的程序员6 小时前
计算机网络:自顶向下方法(第七版)第三章 学习分享(二)
网络·学习·计算机网络
星期五不见面6 小时前
AI学习(三)openclow启动(2)2026/03/05
学习
weixin_443478516 小时前
flutter组件学习之Flex / Expanded弹性布局组件
javascript·学习·flutter
OxyTheCrack6 小时前
【C++】简述Observer观察者设计模式附样例(C++实现)
开发语言·c++·笔记·设计模式
im_AMBER6 小时前
Leetcode 136 最小栈 | 逆波兰表达式求值
数据结构·学习·算法·leetcode·
Xzq2105096 小时前
网络基础学习(一)
网络·学习
Fuliy966 小时前
第三阶段:进化与群体智能 (Evolutionary & Swarm Intelligence)
人工智能·笔记·python·学习·算法