In depth understanding of C++ structure (struct) and common body (union)

  • 2020-11-18 06:23:14
  • OfStack

[

Coding environment: VS2017+Win32+Debug, Win32 represents the application that generates 32bits.

]

Structs (struct) and sharets (union) are data types that already exist in the C language, and C++ has extended them, with the biggest change allowing member functions to be defined in structures and commonalities. The features and USES of both are illustrated in the following examples.

1.struct

Here is an C++ program that USES a structure.


#include <iostream>
using namespace std;

struct Room
{
		int floor;
		int No;
};

struct Student
{
	int age;
	int score;
	Student(int a,int s){
		age=a;
		score=s;
	}
};

int main(int argc,char* argv[])
{

	Room r[3]={{1,101},{2,201},{3,301}};
	Student s(18,89);
	cout<<"the room are:";
	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 operation Results:

[

the room are:1-101 2-201 3-301
the student's age:18 score:89

]

Read the above program and note the following when using structures in C++ :

(1) In C++, the structure is a real data type. When using the structure to define variables, there is no need to put the struct keyword in C or declare it in the way of typedef struct structname structalias first.

(2) C++ extends struct in C, allowing member functions to be defined in struct. Member variables and member functions in struct also have access. In class, the default access is private, while in struct, the default access is public, the only difference between structs and classes. The default access permission for struct members is set to public, which is a policy adopted by C++ to maintain compatibility with the C language.

(3) If no constructor is shown to define in struct, the structure variable can be initialized by specifying the value of the data member in the order of curly braces as in the C language. But once 1 shows that any 1 constructor is defined, it cannot be initialized in this way. If there are only a few data members of type public in class and no constructor is shown to be defined, it can also be initialized with curly braces.

(4) To calculate the size of the structure with sizeof operator, the alignment problem of variables inside the structure should be considered.

2.union

The common body (union), also known as the union, is a special class that inherits from the C chapter. The basic semantics of the class do not change, but it does have some properties of the class (allowing you to define member functions). In practical programming practice, the frequency of use is not as high as struct. The most significant difference compared to struct is that the data members of union share the same segment of memory for the purpose of saving space.

2.1 Basic properties of union

The following procedure is used to examine the space occupied by the union variable and the interaction between member assignments.


#include <iostream>
using namespace std;
union testunion
{
	char c;
	int i;
};

int main(int argc,char* argv[])
{
	cout<<sizeof(testunion)<<endl;
	testunion* pt=new testunion;
	char* p=reinterpret_cast<char*>(pt);
	for(int i=0;i<sizeof(*pt);i++)
		cout<<int(p[i])<<" ";
	cout<<endl;
	cout<<pt->i<<endl;
	pt->c='A';
	cout<<pt->c<<endl;
	for(int i=0;i<sizeof(*pt);i++)
		cout<<int(p[i])<<" ";
	cout<<endl;
	cout<<pt->i<<endl;
	delete pt;
}

Program operation 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 one (int) of the two data members. A change to one of the data members must change the values of all the other data members simultaneously. However, changes to a smaller data member affect only those bytes that the member is supposed to occupy, not the excess bits (the higher bits).

2.2 Advanced features of union

Observe the following procedure.


#include <iostream>
using namespace std;
struct Student
{
	int age;
	int score;
	Student(int a,int s)
	{
		age=a;
		score=s;
	}
};

union testunion
{
	char c;
	int i;
};

class someClass
{
	int num;
public:
	void show(){cout<<num<<endl;}
};

union A
{
	char c;
	int i;
	double d;
	someClass s;
};

union B
{
	char c;
	int i;
	double d;
	B(){d=8.9;}
};

union
{
	char c;
	int i;
	double d;
	void show(){cout<<c<<endl;}
}u={'U'};

int main(int argc,char* argv[])
{
	A a={'A'};
	B b;
	cout<<a.c<<endl;
	cout<<b.d<<endl;
	a.s.show();
	u.show();
	
	// Anonymous shareware 
	union
	{
		int p;
		int q;
	};

	p=3;
	cout<<q<<endl;
}

Program operation Results:

[

A
8.9
65
U
3

]

To read the above program, the following points should be noted:

(1) union can specify access rights of members. By default, struct has the same access rights as public (public).

(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 common body, and it cannot share the space with other data members of the common body. For reference variables, a reference is essentially a pointer constant whose value 1 once initialized is not allowed to be modified. If a common body has reference members, then the common body object 1 cannot be modified after it is created and can only be used as a normal reference, which loses the meaning of the common body.

(4) union allows objects of other classes to become its own data members, but requires that the class belonging to the object cannot define any one of constructor, copy constructor, destructor, assignment operator, virtual function. Because:
(4.1) union data members share memory. During the execution of union constructor, the data members cannot be called as the constructor of class object, otherwise the values of other data members will be changed.
(4.2) Similarly, destructors for union's object members cannot be called because the values of other data members may be meaningless to the object members.
(4.3) the object members union assignment should maintain its original semantics, for the assignment operator overloading, is not recommended because the assignment operator overloading 1 as used for deep "copy" and other occasions, and in the case of object space to share with other variables, the memory resources, introduced "copy", a pointer to the memory resources tend to be Shared with other data members modify body, cannot cause memory resources addressing, causing a memory leak. In addition, there is a memory leak because union's object members do not have custom destructors.
(4.4) For class objects with virtual functions, the pointer to the virtual function table may be overwritten during the initialization of the common body object, resulting in the inaccessibility of the virtual function table and thus the inaccessibility of virtual functions.

(5) If the union type is intended to be used once for the purpose of defining the class and is no longer used, then the name of union may not be given. This is the case for the variable u in the example above, in which case the constructor cannot be defined for the union.

(6) Anonymous common (Anonymous Union), that is, after giving a declaration of an unnamed common body, it does not define any variable of the union, but ends directly with a semicolon. Strictly speaking, an anonymous pool is not a data structure because it cannot be used to define a pool object. It simply indicates that several variables share a slice of memory. In the above example, changes to the variable p actually modify the variable q. As you can see, although variables in the anonymous pool are defined in the same pool, they have the same scope level as any other local variables in the same block. This means that the name of a member in the anonymous pool cannot conflict with any other identifier in the same scope. In addition, there are restrictions on anonymous shares as follows:
(6.1) Anonymous Commons are not allowed to have member functions;
(6.2) Anonymous shares cannot contain private or protected members;
(6.3) Members of a global anonymous pool must be global or static variables.

The above is an in-depth understanding of C++ structures (struct) and shares (union) in detail, more information about C++ structures and shares please pay attention to other related articles on this site!


Related articles: