[C + + learning notes] it’s enough to have an in-depth understanding of C + + structures and utilities!

Time:2021-10-23

Structs and unions are data types that already exist in C language. C + + extends them. The biggest change is to allow member functions to be defined in structures and public bodies. The following will explain their characteristics and usage through examples.

 

1.struct

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

#include

usingnamespacestd;

 

structRoom

{

        intfloor;

        intNo;

};

 

structStudent

{

    intage;

    intscore;

    Student(inta,ints){

        age=a;

        score=s;

    }

};

 

intmain(intargc,char* argv[])

{

 

    Room r[3]={{1,101},{2,201},{3,301}};

    Student s(18,89);

    cout<

    cout<

    cout<

    cout<

    cout<

    getchar();

}

Program running results:

the room are:1-101 2-201 3-301

the student’s age:18 score:89

After reading the above program, you should pay attention to the following points when using structures in C + +

(1) In C + +, structure is a real data type. When using structure to define variables, you do not need to use the struct keyword in C, or use typedef struct structname structalias to declare it first.

(2) C + + extends struct in C to allow member functions to be defined in struct. Member variables and member functions in struct also have access permissions. In class, the default access permission is private, while in struct, the default access permission is public, which is the only difference between a structure and a class. Setting the default access permission of struct members to public is a policy adopted by C + + to maintain compatibility with C language.

(3) If there is no constructor defined in struct, structural variables can be initialized by indicating the values of data members in curly bracket order as in C language. However, once the display defines any constructor, it cannot be initialized in this way. If there are only a few public data members in the class without any constructor defined, curly braces can also be used for initialization.

(4) When calculating the size of a structure with sizeof operator, the alignment of variables inside the structure should be considered.

 

2.union

A union, also known as a union, is a special class inherited from the C language chapter. Its basic semantics has not changed, but has some characteristics of the class (allowing the definition of member functions). In the actual programming practice, the frequency of use is not as high as that of struct. Compared with struct, the most significant difference is that the data members of union share the same memory to save space.

2.1 basic properties of Union

The space occupied by the union variable and the mutual influence of member assignment are investigated through the following procedure.

#include

usingnamespacestd;

uniontestunion

{

    charc;

    inti;

};

 

intmain(intargc,char* argv[])

{

    cout<

    testunion* pt=newtestunion;

    char* p=reinterpret_cast(pt);

    for(inti=0;i

        cout<

    cout<

    cout<i<

    pt->c=’A’;

    cout<c<

    for(inti=0;i

        cout<

    cout<

    cout<i<

    deletept;

}

Program running results:

4

-51 -51 -51 -51

-842150451

A

65 -51 -51 -51

-842150591

It can be seen that the volume of the union testunion variable is 4, which is determined by the larger (int) type of the two data members. Modifying one data member will change the values of all other data members at the same time. However, the modification of a smaller data member will only affect the bytes that the member should occupy, and has no impact on the excess part (high-order bytes).

2.2 advanced features of Union

Observe the following procedure.

#include

usingnamespacestd;

structStudent

{

    intage;

    intscore;

    Student(inta,ints)

    {

        age=a;

        score=s;

    }

};

 

uniontestunion

{

    charc;

    inti;

};

 

classsomeClass

{

    intnum;

public:

    voidshow(){cout<

};

 

unionA

{

    charc;

    inti;

    doubled;

    someClass s;

};

 

unionB

{

    charc;

    inti;

    doubled;

    B(){d=8.9;}

};

 

union

{

    charc;

    inti;

    doubled;

    voidshow(){cout<

}u={‘U’};

 

intmain(intargc,char* argv[])

{

    A a={‘A’};

    B b;

    cout<

    cout<

    a.s.show();

    u.show();

 

//Anonymous community

    union

    {

        intp;

        intq;

    };

 

    p=3;

    cout<

}

Program running results:

A

8.9

65

U

3

 

 

After reading the above procedures, you should pay attention to the following points:

(1) Union can specify the access permissions of members. By default, it has the same permissions (public) as struct.

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

(3) Union cannot have static data members or reference members, because static data members are not actually data members of the community, and it cannot share space with other data members of the community. For a reference variable, a reference is essentially a pointer constant, and its value cannot be modified once initialized. If the community has reference members, the community object cannot be modified once it is created and initialized. It can only be used as a common reference, which loses the significance of the existence of the community.

(4) Union allows objects of other classes to become their own data members, but the class to which the object belongs cannot define any of constructor, copy constructor, designer, assignment operator and virtual function. Because:

(4.1) union data members share memory. When the union constructor is executed, it cannot call the constructor whose data member is a class object, otherwise it will change the values of other data members.

(4.2) similarly, the destructor of the object member of the union cannot be called because the values of other data members may be meaningless to the object member.

(4.3) the assignment of the object member of the union should maintain its original semantics, and it is not recommended to overload the assignment operator, because the overload of the assignment operator is generally used in “deep copy” and other occasions. When the object space is shared with other variables, the memory resources introduced by “deep copy” and the pointer to the memory resources are often modified by other community data members, As a result, memory resources cannot be addressed, resulting in memory leakage. In addition, there is no custom destructor for union object members, which will also lead to memory leakage.

(4.4) for class objects with virtual functions, the pointer of the virtual function table may be overwritten during the initialization of the common object, so the virtual function table cannot be addressed, so it cannot have virtual functions.

(5) If the union type is intended to be used once while defining the class and will not be used in the future, the union name may not be given. This is the case with the variable U in the above example. In this case, the constructor cannot be defined for the union.

(6) Anonymous Union, that is, after a declaration of a common body without a name is given, it does not define any variables of the union, but directly ends with a semicolon. Strictly speaking, anonymous community is not a data structure, because it cannot be used to define community objects. It only indicates that several variables share a memory unit. In the above example, the modification of variable p actually modifies variable Q. It can be seen that although the variables in the anonymous community are defined in the same community, they have the same scope level as any other local variables in the same block. This means that the names of members in an anonymous community cannot conflict with other identifiers in the same scope. In addition, there are the following restrictions on anonymous Commons:

(6.1) anonymous commons are not allowed to have member functions;

(6.2) anonymous community cannot include private or protected members;

(6.3) the members in the global anonymous community must be global or static variables.

The above is to deeply understand the details of C + + structure and union. If you have any questions, please leave a message in the comment area.

 

Finally, if you want to be a programmer and want to master programming quickly, join quicklyLearn Penguin circle

There are senior professional software development engineers to answer all your doubts online ~ introduction to programming language “so easy”

Programming learning books:

 

Programming learning video: