/* * UnionLab.cpp * * Created On:nov, * Author:sodino */#include <iostream>using namespace std;/** * A common body is a special class that can define many different types of data within a common body. * A variable declared as a "shared" type that allows the loading of any type of data defined by the "Commons", * These different types of data share the same piece of memory for space-saving purposes (there is also a space-saving type: bit field). * In addition, as with structs, federated default access is public and has member functions as well. * * In the general data structure each member has its own memory space, the total length of a structure variable is the sum of the length of each member (except for the empty structure, regardless of the boundary adjustment). * and in "Commons", each member shares a memory space! * So the length of a union variable is equal to the length of the longest member of its member. * You can assign a new value to any member of a "common" variable, but you can assign a value to only one member at a time, and the value of the other member has a new value as the memory space is shared. * * This sample code output:<br/> * Udata.schar.first=a udata.schar.second=b * udata.i=0x6261 * */int Main () {Union Uniondata {/* Define a common body */int num;struct {/* defines a structure in the common body */char First;char second;} Schar;} udata;//Shared Body member assignment//assigned to NUM 0x4241, due to shared memory, also equivalent to first assignment 0x41,second assignment 0x42//by ASCII code table: first= ' A ' second= ' B ' udata.num= 0x4241; cout << "udata.schar.first=" << uData.sChar.first << "udata.schar.second=" << UData.sChar.second << Endl; The inverse process of the above steps udata.schar.first= ' a '; /* struct member assignment in Union */uData.sChar.seCond= ' B '; cout << "udata.num=0x" << hex << udata.num << endl;return 0;}
[C + +] Union Common Body Example explained