共同体是一种数据格式,它能够存储不同的数据类型,但只能同时存储其中的一种类型。也就是说,结构可以同时存储int,long和double。共同体只能存储int,long或double。共同体的句法与结构相似,但含义不同。
union one4all
{
int int_val;
long long_val;
double double_val;
};
可以使用one4all来存储int,long或double,条件是在不同的时间进行:
one4all pail;
pail.int_val = 15; // store an int
pail.double_val = 1.38; // store a double, int value is lost
因此,pail有时可以是int,而有时可以是double变量。成员名称标识了变量的容量。由于共同体每次只能存储一个值,因此它必须有足够的空间来存储最大的成员。所以,共同体的长度为其最大成员的长度。
共同体的用途之一是,当数据项使用两种或更多种格式,但不会同时使用时,可节省空间。
匿名共同体没有名称,其成员将成为位于相同地址处的变量。显然,每次只有一个成员是当前的成员。
struct widget
{
char brand[20];
int type;
union
{
long id_num;
char id_char[20];
};
};
代码:
#include <stdio.h>
#include <iostream>
#pragma pack(1)
struct TestStruct
{
int a;
bool b;
float c;
double d;
};
union TestUnion1
{
int a;
bool b;
float c;
double d;
};
union TestUnion2
{
int a;
bool b;
float c;
double d;
TestStruct e;
};
struct widget1
{
char brand[20];
int type;
union test
{
long id_num;
char id_char[20];
}test_val;
};
struct widget2
{
char brand[20];
int type;
union
{
long id_num;
char id_char[20];
};
};
int main()
{
int size1 = sizeof(TestStruct);
int size2 = sizeof(TestUnion1);
int size3 = sizeof(TestUnion2);
//根据union类型定义变量访问
//widget1 a;
//a.test_val.id_char
//匿名union直接访问,位于同地址段
//widget2 b;
//b.id_char
}
size1=17;
size2=8;
size3=17;
#include <stdio.h>
#include <iostream>
#pragma pack(4)
struct TestStruct
{
int a;
bool b;
float c;
double d;
};
union TestUnion1
{
int a;
bool b;
float c;
double d;
};
union TestUnion2
{
int a;
bool b;
float c;
double d;
TestStruct e;
};
struct widget1
{
char brand[20];
int type;
union test
{
long id_num;
char id_char[20];
}test_val;
};
struct widget2
{
char brand[20];
int type;
union
{
long id_num;
char id_char[20];
};
};
int main()
{
int size1 = sizeof(TestStruct);
int size2 = sizeof(TestUnion1);
int size3 = sizeof(TestUnion2);
//根据union类型定义变量访问
//widget1 a;
//a.test_val.id_char
//匿名union直接访问,位于同地址段
//widget2 b;
//b.id_char
}
size1=20;
size2=8;
size3=20;