结构体和联合体的主要区别是:结构体内部数据时分开放的,而联合体所有数据是放在一个地址空间内,我们只能使用其中一个数据。下面举例说明:代码均通过vs2008编译
#include <iostream>
int main ()
{
union
{
int i;
struct
{
char b;
char c;
}str;
}number;
number.i=0x4142;
std::cout<<number.str.b<<number.str.c<<std::endl;
number.str.b='a';number.str.c='b';
std::cout<<number.i<<std::endl;
system("pause");
return 0;
}
输出:BA
25185
这里要说明的一点是,由于编译的大小端对其方式不同,不同的编译器可能会有不同的结果,
对与VS2008来说是高端对其,故第一次输出是BA,也就是0X4142对应的assci码,第二次输出是0X6261,转为十进制为25185,大小端对其在另一篇博文中有详细的介绍。这里不详述