Run the following program and interpret the running results.
#include <iostream>using namespace std;union un{ int i; Char c[4];}; int main () { union un x; x.c[0]= ' A '; x.c[1]= ' B '; X.c[2]= ' C '; x.c[3]= ' D '; cout<<x.i<<endl; return 0;}
#include <iostream>using namespace std;union un{ int i; Char c[4];}; int main () { un x; x.c[0]= ' A '; x.c[1]= ' B '; X.c[2]= ' C '; x.c[3]= ' D '; cout<<x.c[2]<<endl; return 0;}
Watch through the Watch window:
So
The introduction of the structure, the user can easily define new data types, with member variables to store things different aspects of the characteristics. But the structure of each member variable needs to occupy a certain amount of storage space, and the actual requirements there is a certain gap. Introduced a new custom data type Common body (union), much like a struct type, has its own member variable, but all member variables occupy the same memory space. For a shared body variable, at a point in time, only information about one of its members can be stored.
A struct is a structure composed of different data types, where storage space is the sum of the space required by all members, and struct members exist at the same time. And the community is different data types share a storage space, the size of the space is able to accommodate the largest members of the community. The value of a community member cannot exist at the same time.
@ Mayuko
24th Week Project 7-read "community"