Unions
Union is a special class type that can hold only one of its non-static data members at any given time.
Unions were officially added to the NOI syllabus at the introductory level in 2023.
Defining a Union
The class specifier for a union declaration is similar to that of a class or structure:
1 2 3 4 | |
The definition of a union is similar to that of a structure. According to the above definition, MyUnion can also be used as a custom type. The name MyUnion can be omitted.
Accessing/Modifying Member Elements
Similar to structures, members can be accessed using variable_name.member_name.
The memory space occupied by a union is at least the size of its largest member, and all members share the same memory space and address. When a member is assigned a value, due to memory sharing, all other members in the union are overwritten. This means that a union can only hold the value of one member at any given time.
For more usage of unions, refer to cppreference: Union declaration.
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用