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。
相关推荐
94621931zyn61 小时前
关于应用 - Cordova 与 OpenHarmony 混合开发实战
笔记·python
Andy121382 小时前
网页笔记插件(chrome)开发记录
chrome·笔记·mfc
做cv的小昊6 小时前
计算机图形学:【Games101】学习笔记05——着色(插值、高级纹理映射)与几何(基本表示方法)
笔记·opencv·学习·计算机视觉·图形渲染·几何学
车载测试工程师6 小时前
CAPL学习-CAN相关函数-统计API函数
网络·网络协议·学习·capl·canoe
好奇龙猫7 小时前
【AI学习-comfyUI学习-第二十四节-open(contorlnet多重处理)+图生图openpose-各个部分学习】
人工智能·学习
wanzhong23338 小时前
CUDA学习5-矩阵乘法(共享内存版)
深度学习·学习·算法·cuda·高性能计算
PNP Robotics10 小时前
PNP机器人受邀参加英业达具身智能活动
大数据·人工智能·python·学习·机器人
iconball10 小时前
个人用云计算学习笔记 --24 虚拟化、KVM 基础使用与热迁移实验、VMware ESXi笔记
运维·笔记·学习·云计算
是小菜呀!10 小时前
基于深度学习的图像检索系统项目实践
笔记
奕辰杰12 小时前
Netty私人学习笔记
笔记·学习·netty·网络通信·nio