共同體是一種數據格式,它能夠存儲不同的數據類型,但只能同時存儲其中的一種類型。也就是說,結構可以同時存儲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;