C + + 's struct and union

Source: Internet
Author: User

Coded operating Environment: Vs2012+win32+debug
Win32 means that the running platform is the Windows 32bits operating system and the application that generates 32bits.

struct (struct) and union (union) are data types that already exist in the C language. The C + + language extends them, and the biggest change is that it allows member functions to be defined in structs and unions. The characteristics and usage of the two are explained in the following example.

1.struct

The following is a C + + program that uses a structure.

#include <iostream>using namespace STD;structroom{int  Floor;intNo;};structstudent{intAgeintScore; Student (intAints) {age=a;    Score=s; }};intMainintargcChar* argv[]) {r[3]={{1,101},{2,201},{3,301}}; Student S ( -, the);cout<<"The hostel is :";cout<<r[0]. Floor<<"-"<<r[0]. no<<" ";cout<<r[1]. Floor<<"-"<<r[1]. no<<" ";cout<<r[2]. Floor<<"-"<<r[2]. no<<endl;cout<<"The student ' s Age:"<<s.age<<"Score:"<<s.score<<endl; GetChar ();}

Program Run Result:
The are:1-101 2-201 3-301
The student ' s age:18 score:89
Read the above procedure and use the struct (struct) in C + + to pay attention to several points:
(1) in C + +, a struct is a true data type, and it is not necessary to declare it as a struct keyword in C, or in the form of typedef struct STRUCTNAME Structalias, when using structure-defined variables.

(2) C + + expands on the struct in c. to allow the definition of member functions in a struct. Member variables and long-term functions in a struct also have access rights. In class, the default access rights are private, and the default access rights in a struct are public, which is the only difference between structs and classes. The default access permission for struct members is set to public as a strategy for C + + to maintain compatibility with the C language.

(3) If no constructor is defined in the struct, the struct variable can be initialized as if it were in the C language, indicating the value of the data member in curly-brace order. But once the display has defined any one of the constructors, it cannot be initialized this way. If you have only a few public data members in class, and you do not see any constructors defined, you can use curly braces to initialize them.

(4) When calculating the size of the structure with the sizeof operator, it is necessary to consider the alignment of variables within the structure.

Keep in mind that the default access rights in a struct are public, which is the only difference between structs and classes.

2.union

Union (Union) is a special class that is seldom used but useful. It is inherited from the C language chapter, its basic is not changed, but has some characteristics of the class (allow to define member functions). Unlike structs, data members in a union share a piece of memory to achieve space-saving purposes.

Basic properties of 2.1union

Through the following procedures to examine the union variables occupy space, the interaction of the member assignment.

#include <iostream>using namespace STD;Uniontestunion{CharCinti;};intMainintargcChar* argv[]) {cout<<sizeof(testunion) <<endl; testunion* pt=NewTestUnion;Char* p=reinterpret_cast<Char*> (PT); for(intI=0;i<sizeof(*pt); i++)cout<<int(P[i]) <<" ";cout<<endl;cout<<pt->i<<endl; Pt->c=' A ';cout<<pt->c<<endl; for(intI=0;i<sizeof(*pt); i++)cout<<int(P[i]) <<" ";cout<<endl;cout<<pt->i<<endl;DeletePt GetChar ();}

Program Run Result:
4
-51-51-51-51
-842150451
A
65-51-51-51
-842150591

As you can see, the volume of the Union testunion variable is 4, which is determined by the larger (int) type of the two data members. Modifications to one of the data members will certainly change the values of all other data members at the same time. Modifications to smaller data members, however, affect only those bytes that the member should occupy and have no effect on the excess (high byte).

Advanced Features of 2.2union

Observe the following procedure.

#include <iostream>using namespace STD;structstudent{intAgeintScore; Student (intAints) {age=a;    Score=s; }};Uniontestunion{CharCinti;};classsomeclass{intNum Public:voidShow () {cout<<num<<endl; }};Uniona{CharCintIDoubleD SomeClass s;};Unionb{CharCintIDoubleD B () {d=8.9; }};Union{CharCintIDoubleDvoidShow () {cout<<c<<endl; }}u={' U '};intMainintargcChar* argv[]) {A a={' A '}; b b;cout<<a.c<<endl;cout<<b.d<<endl;    A.s.show (); U.show ();Union{intPintQ    }; p=3;cout<<q<<endl; GetChar ();}

Program Run Result:
A
8.9
65
U
3
To read the above procedures, the following points need to be noted:

(1) Union can specify access rights for a member, by default, with the same permissions (public) as a struct.

(2) Union may also define member functions, including constructors and destructors. Unlike a struct, it cannot be inherited as a base class.

(3) A union cannot have a static data member or a reference member because a static data member is not actually a data member of a union and it cannot share space with other data members of the Union. For reference variables, a reference is essentially a constant, and its value is not allowed to be modified once it is initialized. If a union has a reference member, it cannot be modified after the creation of the Union object, and can only be used as a normal reference, which loses the meaning of the existence of the Union.

(4) union allows an object of another class to be its own data member, but requires that the class to which the class object belongs cannot be defined constructor,copy constructor,destructor,copy assignment operator, virtual Any one of the function. So design the current-domain shared memory considerations.

(5) If the union type is intended to be used at the same time as the class is defined and is no longer used later, the union name may not be given. As in the above example, the variable U is the case, in which case the constructor cannot be defined for the Union.

(6) Anonymous Union (anonymous union), which gives a declaration of a union without a name, does not define any of the union's variables, but instead directly ends with a semicolon. Strictly speaking, anonymous syndication is not a data structure, because it cannot be used to define variables, it simply indicates that several variables share a single piece of the deposit element. In the above example, the modification of the variable p is actually the change of the variable Q. As you can see, although the variables in the anonymous union are defined in a union declaration, they have the same scope level as any other local variables of the same program block. This means that the names of members within an anonymous union cannot conflict with other identifiers within the same scope.

In addition, the following restrictions exist for anonymous Federation:
-Anonymous unions are not allowed to have member functions;
-Anonymous unions also cannot contain private or protected members;
-A member in a global anonymous Union must be a global or static variable.

Reference documents

[1] Advanced Step-by-step tutorials for C + + Chen Gang. Wuhan University Press

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + 's struct and union

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.