Union is an unnoticed keyword, and it does not appear in C + + for the sake of inheriting the C language. Its role is mainly to save memory space, in embedded programming is useful. But in C + +, which is designed for contemporary microcomputers, it is not useless. Take a look at the following code:
class a{private: int a[]; Public : A (int N): a[0] (n) {}}; // Wrong Code
Do you think this code can be compiled? Yes, that should be the case. But to run the compiler, you will get the following error expected ' (' before ' [' token:a (int n): a[0] (n) {}. The amount ... It seems that array elements cannot be used for list initialization. At this point, we can use union to solve the problem skillfully.
class a{private: Union { int a[]; int a0; }; Public : A (int N): A0 (n) {}};
The principle is not difficult to understand, according to the Union mechanism, A0 and a[0] is actually a common int, that is, A0 and a[0] the same address, the initialization of A0 is also the initialization of a[0].
C + + Union refinement