今天在看内存池的内容,看到联合,虽然见过这个关键词但从未了解过。最近闲来无聊这些都写来补补吧。
参考博客:
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;
}
};
2243

被折叠的 条评论
为什么被折叠?



