C++ The union Data Structure
A union is like a struct in that it generally has several fields, all of which are public by default. Unlike a struct, however, only one of the fields is used at any given time.
In other words, it is a structure that allows the same storage space to be used to store values of different data types at different times.
Unions can be used to conserve memory when a structure is needed in which several pieces of information of different types must be represented but only one will be used at a time, as when the components of a container must contain values of differing data types.
The usual syntax for a union is illustrated by
1 | union Test{ |
1 | int main() |
When the above code is executed, the program will output the following result
1 | 0 |
对k的赋值因为是union,要共享内存,所以从union的首地址开始放置,首地址开始的位置其实是x的位置,这样原来内存中x的位置就被k所赋的值代替了,就变为0了。
And this is basically how union works.