C++自学笔记31(union联合体)

对同一个数组数据,提供多种操作方法。看栗子。

#include <isotream>

int main()
{
    struct A
    {
        union
        {
            float a;
            int b;
        }
    };
    
    A e;
    A.a = 2;
    std::cout<<A.a<<","<<A.b<<endl;
    std::cin.get();
}

 打印出的是2,1703741824

2是浮点的2,1703741824是浮点形式的2的字节表示,就是取得了浮点2的内存将其解释成整型。

这就与上一个笔记中的类型转换相对应了。

我们可以看到我对于b并没与做什么变化,却已经与2转换了类型,意味着union内部其实只有一个成员,两个变量指向了一个地址。我们再来看个栗子。

#include <iostream>
#inclued <vector>

struct Vector2
{
  float x,y;  
};

struct Vector4
{
  float x,y,z,w;  
};

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

int main()
{

    sad::cin.get();
}

我们看到思维向量实际上就是两个二维向量,那怎么用两个Vector2表示一个Vector4呢?我们可以设计两个二维向量a b,其中a对应着四维的xy,b对应着四维的zw。

#include <iostream>
#inclued <vector>

struct Vector2
{
    float x,y;  
};

struct Vector4
{
    union
    { 
        struct
        {
          float x,y,z,w;  
        };
    }
};

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

int main()
{

    sad::cin.get();
}

我们对四维向量做出以上改变,注意到struct实际上没有对其命名(匿名结构体)将xyzw结构体作为一个成员放在union中。为什么这么做?还记说union只有一个成员,如果不用匿名结构体,那么xyzw指向的都是一个地址,这显然是不对的。

我们继续的代码更改。

#include <iostream>
#inclued <vector>

struct Vector2
{
    float x,y;  
};

struct Vector4
{
    union
    { 
        struct
        {
          float x,y,z,w;  
        };
        struct
        {
          vector a,b;  
        };
    }
};

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

int main()
{
    Vector4 vector = {1.0f,2.0f,3.0f,4.0f};
    PrintfVector2(a);
    PrintfVector2(b);
    vector.z = 99;
    PrintfVector2(a);
    PrintfVector2(b);

    sad::cin.get();
}

union下a与xy占据相同内存,b与zw占据相同内存,就是我们有两个方式操纵四维变量。

打印效果为

1,2

3 , 4

1,2

99 , 4

union为我们提供了对于相同变量进行不同方式操作的关键字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值