C++共用体与结构体区别-C++ union与struct的区别-嗨客网
Fri Nov 25 2022 02:45:59 GMT+0000 (Coordinated Universal Time)
Saved by
@leawoliu
#include <iostream>
using namespace std;
struct StructName{
int a;
float b;
char c;
};
union UnionName{
int a;
float b;
char c;
};
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
int sizeStruct = sizeof(struct StructName);
int sizeUnion = sizeof(union UnionName);
cout << "sizeStruct = " << sizeStruct << " sizeUnion = " << sizeUnion << endl;
return 0;
}
content_copyCOPY
结构体的各个成员会占用不同的内存,互相之间没有影响,而共用体的所有成员占用同一段内存,修改一个成员会影响其余所有成员。
结构体占用的内存大于等于所有成员占用的内存的总和(成员之间可能会存在缝隙),共用体占用的内存等于最长的成员占用的内存。
共用体使用了内存覆盖技术,同一时刻只能保存一个成员的值,如果对新的成员赋值,就会把原来成员的值覆盖掉。
https://haicoder.net/cpp/cpp-struct-union.html
Comments