[C++ Core] Detailed Explanation of Structures and Unions

1. Structure

1.1 Basic concept of structure

The struct belongs to the usercustom data type, allowing users to store different data types

1.2 Structure definition and use

grammar: struct 结构体名 { 结构体成员列表 };

There are three ways to create variables through structures:

  • struct structure name variable name
  • struct structure name variable name = { member 1 value, member 2 value...}
  • Create variables by the way when defining the structure

Example:

#include<iostream>
#include<string>
using namespace std;

//结构体定义
struct student
{
    
    
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
}stu3; //结构体变量创建方式3 


int main() {
    
    

	//结构体变量创建方式1
	struct student stu1; //struct 关键字可以省略

	stu1.name = "张三";
	stu1.age = 18;
	stu1.score = 100;
	cout << "姓名:" << stu1.name << " 年龄:" << stu1.age  << " 分数:" << stu1.score << endl;

	//结构体变量创建方式2
	struct student stu2 = {
    
     "李四",19,60 };
	cout << "姓名:" << stu2.name << " 年龄:" << stu2.age  << " 分数:" << stu2.score << endl;

	stu3.name = "王五";
	stu3.age = 18;
	stu3.score = 80;
	cout << "姓名:" << stu3.name << " 年龄:" << stu3.age  << " 分数:" << stu3.score << endl;

	return 0;
}

Summary 1: The keyword when defining a structure is struct, which cannot be omitted.
Summary 2: When creating a structure variable, the keyword struct can be omitted.
Summary 3: A structure variable uses the operator ''.'' to access members

1.3 Structure array

Function: put the custom structure into the array for easy maintenance

grammar: struct 结构体名 数组名[元素个数] = { {} , {} , ... {} }

Example:

#include<iostream>
#include<string>
using namespace std;

//结构体定义
struct student
{
    
    
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
}

int main() {
    
    
	
	//结构体数组
	struct student arr[3]=
	{
    
    
		{
    
    "张三",18,80 },
		{
    
    "李四",19,60 },
		{
    
    "王五",20,70 }
	};

	for (int i = 0; i < 3; i++)
	{
    
    
		cout << "姓名:" << arr[i].name << " 年龄:" << arr[i].age << " 分数:" << arr[i].score << endl;
	}

	system("pause");
	return 0;
}

1.4 Structure Pointer

Function: access the members of the structure through the pointer, and use the operator -> to access the properties of the structure through the pointer of the structure

Example:

#include<iostream>
#include<string>
using namespace std;

//结构体定义
struct student
{
    
    
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};


int main() {
    
    
	
	struct student stu = {
    
     "张三",18,100, };
	
	struct student * p = &stu;
	
	p->score = 80; //指针通过 -> 操作符可以访问成员

	cout << "姓名:" << p->name << " 年龄:" << p->age << " 分数:" << p->score << endl;

	return 0;
}

Summary: The structure pointer can access the members of the structure through the -> operator

1.5 Structure Nested Structure

Role: A member of a structure can be another structure

For example: each teacher tutors a student, and in the structure of a teacher, record the structure of a student

Example:

#include<iostream>
#include<string>

using namespace std;

//学生结构体定义
struct student
{
    
    
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

//教师结构体定义
struct teacher
{
    
    
    //成员列表
	int id; //职工编号
	string name;  //教师姓名
	int age;   //教师年龄
	struct student stu; //子结构体 学生
};


int main() {
    
    

	struct teacher t1;
	t1.id = 10000;
	t1.name = "老王";
	t1.age = 40;

	t1.stu.name = "张三";
	t1.stu.age = 18;
	t1.stu.score = 100;

	cout << "教师 职工编号: " << t1.id << " 姓名: " << t1.name << " 年龄: " << t1.age << endl;
	
	cout << "辅导学员 姓名: " << t1.stu.name << " 年龄:" << t1.stu.age << " 考试分数: " << t1.stu.score << endl;

	return 0;
}

Summary: In a structure, another structure can be defined as a member to solve practical problems

1.6 Structure as function parameter

Role: pass the structure as a parameter to the function

There are two delivery methods: 值传递,地址传递

Example:

#include<iostream>
#include<string>

using namespace std;

//学生结构体定义
struct student
{
    
    
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

//值传递
void printStudent(student stu )
{
    
    
	stu.age = 28;
	cout << "子函数中 姓名:" << stu.name << " 年龄: " << stu.age  << " 分数:" << stu.score << endl;
}

//地址传递
void printStudent2(student *stu)
{
    
    
	stu->age = 28;
	cout << "子函数中 姓名:" << stu->name << " 年龄: " << stu->age  << " 分数:" << stu->score << endl;
}

int main() {
    
    

	student stu = {
    
     "张三",18,100};
	//值传递
	printStudent(stu);
	cout << "主函数中 姓名:" << stu.name << " 年龄: " << stu.age << " 分数:" << stu.score << endl;

	cout << endl;

	//地址传递
	printStudent2(&stu);
	cout << "主函数中 姓名:" << stu.name << " 年龄: " << stu.age  << " 分数:" << stu.score << endl;

	return 0;
}

Summary: If you don't want to modify the data in the main function, pass it by value, otherwise pass it by address

1.7 Const usage scenarios in structures

Function: use const to prevent misoperation

Example:

#include<iostream>
#include<string>
using namespace std;

//学生结构体定义
struct student
{
    
    
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
};

//const使用场景
void printStudent(const student *stu) //加const防止函数体中的误操作
{
    
    
	//stu->age = 100; //操作失败,因为加了const修饰
	cout << "姓名:" << stu->name << " 年龄:" << stu->age << " 分数:" << stu->score << endl;

}

int main() {
    
    

	student stu = {
    
     "张三",18,100 };

	printStudent(&stu);
	
	return 0;
}

1.8 Structure case

1.8.1 Case 1

Case description:

The school is doing a graduation project. Each teacher leads 5 students, and there are 3 teachers in total. The requirements are as follows:

  • Design the structure of students and teachers, where in the structure of teachers, there are teacher names and an array storing 5 students as members;
  • The members of the students have names and test scores, create an array to store 3 teachers, and assign values ​​to each teacher and the students they bring through the function
  • Finally, the teacher data and the student data brought by the teacher are printed out.

Example:

#include<iostream>
#include<string>
#include<ctime>
using namespace std;

struct Student
{
    
    
	string name;
	int score;
};
struct Teacher
{
    
    
	string name;
	Student sArray[5];
};

void allocateSpace(Teacher tArray[] , int len)
{
    
    
	string tName = "教师";
	string sName = "学生";
	string nameSeed = "ABCDE";
	for (int i = 0; i < len; i++)
	{
    
    
		tArray[i].name = tName + nameSeed[i];
		
		for (int j = 0; j < 5; j++)
		{
    
    
			tArray[i].sArray[j].name = sName + nameSeed[j];
			tArray[i].sArray[j].score = rand() % 61 + 40;
		}
	}
}

void printTeachers(Teacher tArray[], int len)
{
    
    
	for (int i = 0; i < len; i++)
	{
    
    
		cout << tArray[i].name << endl;
		for (int j = 0; j < 5; j++)
		{
    
    
			cout << "\t姓名:" << tArray[i].sArray[j].name << " 分数:" << tArray[i].sArray[j].score << endl;
		}
	}
}

int main() {
    
    

	srand((unsigned int)time(NULL)); //随机数种子 头文件 #include <ctime>

	Teacher tArray[3]; //老师数组

	int len = sizeof(tArray) / sizeof(Teacher);

	allocateSpace(tArray, len); //创建数据

	printTeachers(tArray, len); //打印数据

	return 0;
}

1.8.2 Case 2

Case description:

Design a structure of heroes, including member names, ages, and genders; create an array of structures, and store 5 heroes in the array.

Through the bubble sorting algorithm, sort the heroes in the array in ascending order according to age, and finally print the sorted results.

The information of the five heroes is as follows:

		{"刘备",23,"男"},
		{"关羽",22,"男"},
		{"张飞",20,"男"},
		{"赵云",21,"男"},
		{"貂蝉",19,"女"},

Example:

#include<iostream>
#include<string>
using namespace std;

//英雄结构体
struct hero
{
    
    
	string name;
	int age;
	string sex;
};
//冒泡排序
void bubbleSort(hero arr[] , int len)
{
    
    
	for (int i = 0; i < len - 1; i++)
	{
    
    
		for (int j = 0; j < len - 1 - i; j++)
		{
    
    
			if (arr[j].age > arr[j + 1].age)
			{
    
    
				hero temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}
//打印数组
void printHeros(hero arr[], int len)
{
    
    
	for (int i = 0; i < len; i++)
	{
    
    
		cout << "姓名: " << arr[i].name << " 性别: " << arr[i].sex << " 年龄: " << arr[i].age << endl;
	}
}

int main() {
    
    

	struct hero arr[5] =
	{
    
    
		{
    
    "刘备",23,"男"},
		{
    
    "关羽",22,"男"},
		{
    
    "张飞",20,"男"},
		{
    
    "赵云",21,"男"},
		{
    
    "貂蝉",19,"女"},
	};

	int len = sizeof(arr) / sizeof(hero); //获取数组元素个数

	bubbleSort(arr, len); //排序

	printHeros(arr, len); //打印

	system("pause");
	return 0;
}

2. Union

Union is union , which is a special class. Defined by the keyword union, a union can have multiple data members. For example

union Token{
    
    
   char cval;
   int ival;
   double dval;
};

The above code defines a union named Token, which contains 3 data members.

2.1 Advantages of the Union

The advantages of the union are as follows:

1. Use in segments
2. Save space: For several variables that do not appear at the same time in a certain period of time, we can save memory space by using unions.
3. Instead of strong type conversion. For example:In network programming, it is often used to pass in a string of data, which will be passed to different functions in the form of parameters. Therefore, a union can be used, so that the union is full of function pointers, pointing to different functions at the same time. Therefore, programming efficiency is improved and space is saved.

2.2 Limitations of union

Object members in union cannot have constructors, destructors, and overloaded copy assignment operators; object members of object members cannot have them, and so on,
union cannot inherit

2.3 union case

Use union to save grade information and output

#include <iostream>
using namespace std;

class ExamInfo {
    
    
    
public:
    ExamInfo(string n, char g):name(n),mode(GRADE),grade(g){
    
    }
    ExamInfo(string n, bool p):name(n),mode(PASS),grade(p){
    
    }
    ExamInfo(string n, int p):name(n),mode(PERCENTAGE),grade(p){
    
    }

    void show();

private:
    string name;
    enum {
    
    GRADE, PASS, PERCENTAGE} mode;
    union {
    
    
        char grade;
        bool pass;
        int percent;
    };

};

void ExamInfo::show() {
    
    
    cout << name << ": ";

    switch(mode) {
    
    
        case GRADE: cout << grade;break;
        case PASS: cout << pass ? "PASS" : "FAIL";break;
        case PERCENTAGE: cout << percent;break;
    }

    cout << endl;
}

int main() {
    
    

    ExamInfo examInfo1("English", 'B');
    ExamInfo examInfo2("Calculus", true);
    ExamInfo examInfo3("C++ Programming", 85);

    examInfo1.show();       // English: B
    examInfo2.show();       // Calculus: 1
    examInfo3.show();       // C++ Programming: 85
    
    return 0;
}

Guess you like

Origin blog.csdn.net/cui_yonghua/article/details/131364481