代码如下
#include <iostream>
#include <string>
using namespace std;
typedef struct t_in_struct1
{
int var1;
int var2;
}name_in_struct1;
typedef struct t_in_struct2
{
int var3;
int var4;
}name_in_struct2;
typedef struct t_struct {
int a;
union {
name_in_struct1 in_struct1;
name_in_struct2 in_struct2;
}union_name;
}name_struct;
int main() {
name_struct structA;
structA.a = 0;
structA.union_name.in_struct1.var1 = 1;
structA.union_name.in_struct1.var2 = 2;
structA.union_name.in_struct2.var3 = 3;
structA.union_name.in_struct2.var4 = 4;
cout << "0 "<<endl;
cout << "structA.a = " << structA.a << endl;
cout << "structA.union_name.in_struct1.var1 = " << structA.union_name.in_struct1.var1 << endl;
cout << "structA.union_name.in_struct1.var2 = " << structA.union_name.in_struct1.var2 << endl;
cout << "structA.union_name.in_struct2.var3 = " << structA.union_name.in_struct2.var3 << endl;
cout << "structA.union_name.in_struct2.var4 = " << structA.union_name.in_struct2.var4 << endl;
cout << "1 " << endl;
return 0;
}
结果如下