联合 union

 

今天在看内存池的内容,看到联合,虽然见过这个关键词但从未了解过。最近闲来无聊这些都写来补补吧。

参考博客:

https://blog.youkuaiyun.com/dreamback1987/article/details/8504943

联合其实看完也没什么写的了,就是遵循眼过千遍不如手过一遍的原则吧。

联合:多个变量共用一块内存,多个变量中取最大的为联合大小。例:

//
//  main.cpp
//  test_union
//
//  Created by Wtayu on 2019/7/29.
//  Copyright © 2019 Wtayu. All rights reserved.
//

#include <iostream>
class A
{
    int a;
    union u
    {
        char c1;
        int ui;
        char c2;
    };
};

int main(int argc, const char * argv[]) {
    std::cout<<"class A:"<<sizeof(A)<<std::endl;
    return 0;
}

输出:

class A:4
Program ended with exit code: 0

好了这里其实就已经联合已经测试完了。但是实际的应用是怎样的呢?希望有大佬可以分享给我吧。我看到上面那个博客内编写协议时的写法很好所以抄到下面吧,但是我就不解释了,想看解释就看下上面那个链接的博客吧~~

如下:

struct structA 
{
    int a;
    char b;
};
struct structB 
{
    char a;
    short b;
};
struct structC
{
    int a;
    char b;
    float c;
}


struct CommuPacket
{
    int iPacketType;  //报文类型标志
    union         //每次传送的是三种报文中的一种,使用union
    {
        struct structA packetA;
        struct structB packetB;
        struct structC packetC;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值