A union is a special class type that can hold only one of its non-static data members at a time.
Unions were officially added to the introductory level of the NOI syllabus in 2023.
Defining a union
The class specifier in a union declaration is similar to the declaration of a class or a struct:
union MyUnion {
int x;
long long y;
} x;
The definition of a union is similar to that of a struct. According to the definition above, MyUnion can likewise be used as a user-defined type. The name MyUnion may be omitted.
Accessing/modifying member elements
As with a struct, use 变量名.成员名 for access.
The memory occupied by a union is no smaller than the size of its largest member, and all members share the same memory space and address. When one member is assigned a value, the other members of the union are overwritten because the memory is shared. In other words, a union can store the value of only one member at a time.
For more uses of unions, see cppreference: union declaration.