[C + +] Union Common Body Example explained

Source: Internet
Author: User

/* * 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.