Use the constructor to complete the initialization of the structure

Preface

Speaking of structure initialization, people naturally think of defining a structure variable first, and then assigning values ​​to the elements one by one to achieve the purpose of initialization.

But if you do this, it is not convenient when there are many variables in the structure. Here is a method of using the "constructor" to initialize for readers to learn.

The so-called constructor is a function used to initialize the structure, which is directly defined in the structure.
A feature of the constructor is that it does not need to write the return type, and the function name is the same as the structure name.

example:

struct student
{
    
    
	int id;
	char name;
	//默认生成的构造函数
	student(){
    
    }
};

"Student(){}" is the constructor generated by default. You can see that the function name of this constructor is the same as the structure type name; it has no return type, so nothing is written before student; it has no parameters, so the parentheses are Empty; it also has no function body, so the curly braces are also empty. Because of the existence of this constructor, you can directly define the variable of the student type without initializing it (because it does not allow the user to provide any initialization parameters)

So, what should I do if I want to manually provide the initialization parameters of id and name?

struct student
{
    
    
	int id;
	char name;
	//下面的参数用以对结构体内部变量进行赋值
	student(int _id,char _name)
	{
    
    
		id=_id;
		name=_name;
	}
};

Of course, the constructor can also be abbreviated as one line

struct student
{
    
    
	int id;
	char name;
	//下面的参数用以对结构体内部变量进行赋值
	student(int _id,char _name) : id(_id),name(_nmae)	{
    
    }
};

Insert picture description here
Note: If you redefine the constructor yourself, you cannot define the constructor variable without initializing it.
That is to say, the default constructor "student(){}" has been overwritten at this time. In order to define structure variables without initializing them,
and to enjoy the convenience of initialization, you can add "student(){}" manually. This means that as long as the number and types of parameters are not exactly the same,
you can define any number of constructors to suit different initialization occasions.
E.g:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/114580713