2.1.3 构造数据类型(6)
在完成以上3个赋值运算后,a.f是有效的,a.i和a.c已经无意义了。
在程序中经常使用结构体与共用体相互嵌套的形式。即共用体类型的成员可以是结构体类型,或者结构体类型的成员是共用体类型。
4) 共用体应用举例
例2-5 通过执行下面的程序,证明3个字符串共用同一个内存空间。
- #include<iostream.h>
- #include<string.h>
- void main()
- {
- union some_strings
- {
- char command_line[80];
- char error_message[80];
- char help_text[80];
- }strs;
- strcpy(strs.error_message,"Press1,2or 3.");
- cout<<strs.error_message<<endl<<strs.command_line<<endl;
- cout<<strs.help_text<<endl;
- cout<<"Press Enter to continue."<<endl;
- }
该程序的输出结果如图2-6所示。
