C++ 联合(2)

 1 #include<iostream>
 2 using namespace std;
 3 class someClass{
 4     int num;
 5 public:
 6     void show(){
 7         cout<<num<<endl;
 8     }
 9 };
10 union A{
11     char c;
12     int i;
13     double d;
14     someClass s;
15 };
16 union B{
17     char c;
18     int i;
19     double d;
20     B(){
21         d = 8.9;
22     }
23 };
24 union{
25     char c;
26     int i;
27     double d;
28     void show(){
29         cout<<c<<endl;
30     }
31 }u={'U'};
32 
33 int main(){
34     A a = {'A'};
35     B b ;
36     
37     cout<<a.c<<endl; //输出A
38     cout<<b.d<<endl;//输出8.9
39     a.s.show();//输出65,就是A
40     u.show();//输出U
41 
42     union{ //匿名联合
43         int p;
44         int q;
45     };
46     p = 3;
47     cout<<q<<endl;//输出3
48 }
49 1、union可以指定成员的访问权限,默认情况是public
50 2、union也可以定义成员函数,包括构造函数和析构函数,但是,它不能作为基类使用,成员函数不能为虚函数。
51 3、union允许其他类的对象成为它的数据成员,但是要求该对象的所属类不能定义构造函数、析构函数或者赋值操作符函数。
52 4、匿名联合并不是一种数据类型、因为它不用来定义变量,它只是指明若干个变量共享一片存储单元。
原文地址:https://www.cnblogs.com/teng-IT/p/6014834.html