There is such a special function in C++. It is a function with the same name as the class name in a class and has no return value. As long as we define an object of the class, the system will automatically call it for special initialization of the object. In most cases, because we do not define a constructor , the system will generate a default form and hidden constructor by default. The function body of this constructor is empty and therefore does not have any function.
Next, we will teach you how to define your own constructor. The user needs to define at least one constructor by himself. The system will no longer automatically generate it, but will select the most matching one to call based on the user-defined constructor.
For example, still using the Student class, we add a constructor with default parameters. The code is as follows:
#include<iostream>#include<Cstring>usingnamespacestd;classStudent{private:intnum;//student number charname[100];//name intscore;//score public:Student(intn,char*str,ints);intprint( );intSet(intn,char*str,ints);};Student::Student(intn,char*str,ints){num=n;strcpy(name,str);score=s;cout<<Constructor<< endl;}intStudent::print(){cout<<num<<<<name<<<<score;return0;}intStudent::Set(intn,char*str,ints){num=n;strcpy(name, str);score=s;}intmain(){StudentA(100,dotcpp,11);A.print();return0;}
That is, the constructor can be called at the same time as it is defined to realize the initialization function. The operation is as follows:
It should be noted that since we have defined a constructor with default parameters in the class, the system will not automatically generate it. At this time, we also need to pass in three default initial values when defining the object, because the constructor can Overloading, the system will find the most matching function, but if it is not defined as a constructor with default parameters, an error will be reported. Please experiment on your own!