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。
相关推荐
yatingliu20191 小时前
HiveQL | 个人学习笔记
hive·笔记·sql·学习
郭庆汝1 小时前
CMake概述用法详细笔记
笔记
武当豆豆1 小时前
C++编程学习(第25天)
开发语言·c++·学习
张人玉1 小时前
XML 序列化与操作详解笔记
xml·前端·笔记
风和日丽 随波逐流1 小时前
java17学习笔记-Deprecate the Applet API for Removal
笔记·学习
淮北也生橘122 小时前
Linux的ALSA音频框架学习笔记
linux·笔记·学习
diablobaal2 小时前
云计算学习100天-第17天
学习
果粒橙_LGC3 小时前
论文阅读系列(一)Qwen-Image Technical Report
论文阅读·人工智能·学习
yiqiqukanhaiba5 小时前
STM32学习笔记13-通信协议I2C&MPU6050&I2C软件控制
笔记·stm32·学习
code bean5 小时前
【halcon】Halcon 开发笔记: gray_histo_abs 报错陷阱
笔记