联合由两个或更多个变量组成,这些变量共用相同的内存地址。正是因为如此,在程序中可以使用联合来根据不同的情况对包含不同数据类型的信息进行存储和访问。也就是说,联合为几种不同类型数据提供了一个一致的接口,这样联合以最简单的形式体现了“一种接口,多种方法”的概念。
下面程序演示上述行为:
[C++] 纯文本查看 复制代码 #include <iostream>
using namespace std;
struct byte {
unsigned a : 1;
unsigned b : 1;
unsigned c : 1;
unsigned d : 1;
unsigned e : 1;
unsigned f : 1;
unsigned g : 1;
unsigned h : 1;
};
union bits {
char ch;
struct byte bit;
}ascii;
void disp_bits (bits b);
int main()
{
do {
cout << "Input a char for display its ASCII: ";
cin >> ascii.ch;
cout << "You input \'" << ascii.ch << "\'" << " and its binary ascii is:" << '\n';
cout << "-----------------------\n";
disp_bits(ascii);
}while (ascii.ch != 'q');
return 0;
}
void disp_bits (bits b)
{
if (b.bit.h) cout << "1 ";
else cout << "0 ";
if (b.bit.g) cout << "1 ";
else cout << "0 ";
if (b.bit.f) cout << "1 ";
else cout << "0 ";
if (b.bit.e) cout << "1 ";
else cout << "0 ";
if (b.bit.d) cout << "1 ";
else cout << "0 ";
if (b.bit.c) cout << "1 ";
else cout << "0 ";
if (b.bit.b) cout << "1 ";
else cout << "0 ";
if (b.bit.a) cout << "1 ";
else cout << "0 ";
cout << "\n";
}
运行输出:$ ./union
Input a char for display its ASCII: a
You input 'a' and its binary ascii is:
-----------------------
0 1 1 0 0 0 0 1
Input a char for display its ASCII: b
You input 'b' and its binary ascii is:
-----------------------
0 1 1 0 0 0 1 0
Input a char for display its ASCII: c
You input 'c' and its binary ascii is:
-----------------------
0 1 1 0 0 0 1 1
Input a char for display its ASCII: q
You input 'q' and its binary ascii is:
-----------------------
0 1 1 1 0 0 0 1 上面程序在按下 'q' 键时退出,退出之前仍然会打印出 'q' 的 ASCII 码。
在 C++ 中有一种特殊的联合类型---匿名联合。在 “匿名联合” 里不需要指定类型的名字,而且不能定义匿名联合类型的对象。匿名联合只是告诉编译器它所包含的成员将共用相同的内存地址。此外,我们还可以直接使用匿名联合中的变量,而不需要再通过点运算符。
示例代码:
[C++] 纯文本查看 复制代码 #include <iostream>
using namespace std;
int main()
{
union {
short int count;
char ch[2];
};
ch[0] = 'X';
ch[1] = 'Y';
cout << "union as chars: " << ch[0] << ch[1] << '\n';
cout << "union as integer: " << count << '\n';
return 0;
}
运行输出:$ ./anonymous_unio
union as chars: XY
union as integer: 22872 上面程序中,将字符 X 和 Y 分别放入 count 的低字节和高字节中,这样就构成了整型变量 count 的值 22872 。
使用匿名联合时,是以普通变量而不是联合成员的方式来访问 count 和 ch 的。另外需要注意的是,匿名联合中的成员和 main() 中的其它局部变量作用一致,因此在 main() 中不能定义出和匿名联合中成员相同名字的局部变量。
匿名联合的作用就是告诉编译器我们希望两个或多个变量使用相同的内存地址,除此之外,它的成员和其它的普通变量用法是一致的。 |