/*
**test24.cpp : Defines the entry point for the console application.
**系统winXP SP3 32位.
**联合与枚举
*/
#include "stdafx.h"
#include "iostream.h"
union U1{ //联合在内存中占据空间的大小取决于其成员最大的那个
int iNum;
char cNum;
double dNum;
};
enum WORD {a, b = 3, c , d , e = 7 , f}; //值分别为0,3,4,5,7,8
int main(int argc, char* argv[])
{
U1 u1;
cout<<sizeof(u1)<<endl; //8
u1.iNum = 4;
printf("u1.iNum = %d\n", u1.iNum); //4
printf("u1.cNum = %d\n", u1.cNum); //4
printf("u1.dNum = %d\n", u1.dNum); //4
u1.cNum = 'a';
printf("u1.iNum = %c\n", u1.iNum); //a
printf("u1.cNum = %c\n", u1.cNum); //a
printf("u1.dNum = %c\n", u1.dNum); //a
u1.dNum = 1.23;
printf("u1.iNum = %f\n", u1.iNum); //0.000000
printf("u1.cNum = %f\n", u1.cNum); //0.000000
printf("u1.dNum = %f\n", u1.dNum); //1.230000
WORD word1 = a;
cout<<sizeof(WORD)<<endl; //4,枚举类型的大小等于sizeof(int)
cout<<word1<<endl; //0
return 0;
}
Tips1:联合:不同数据成员共享存储空间,不同数据类型成员之间可实现自动转换,与结构体不同的是联合只能在同一时间储存一个成员的值(如果同时访问联合内的多个成员,智慧有一个值是正确的)。