联合判别式
联合只能用第一个成员类型的值进行初始化。且初始化必须放在一个大括号里面.
- 联合体是所有的成员都共用一块内存,如下
#include <iostream>
using namespace std;
union s
{
int a;
char c;
};
int main()
{
union s s1 = {97}; //如果将char,和int调换位置,则由于内存中高24位不确定,可能出现乱码
cout << s1.a << endl;
cout << s1.c << endl;
}
union的判别式(discriminant)
在使用联合对象时,我们往往得确定union对象当前存储的是什么类型的值,所以,更常见的用法是使用 union的判别式(discriminant).
#include <iostream>
using namespace std;
enum T{INT,CHAR};
struct Data{
T type;
union {
char c;//1
int a;// 4
//}val;
};
};
/*void out_data(Data *p) //结构体中的联合体有变量val
{
if(p->type == INT)
cout << p->val.a << endl;
else if(p->type == CHAR)
cout << p->val.c << endl;
}
*/
void out_data(Data *p) //结构体中的联合体没有声明变量,则直接引用
{
if(p->type == INT)
cout << p->a << endl;
else if(p->type == CHAR)
cout << p->c << endl;
}
int main()
{
Data d;
d.type = CHAR;
d.c = 97;
out_data(&d);
return 0;
}