As we all know, the job of the constructor is to ensure that each object's data member has an appropriate initial value.
// Assume that name (string), stunum (INT), and grade (INT) are data members of the class myclass. Class myclass: myclass () {name = "Class 1 "; stunum = 60; grade = 2 ;}
I always think that the three rows in the above constructor function are the initialization of the data members. Today, an occasional bug gave me the lead and looked at primer to know that the value assignment is not initialization ......
In fact, the execution of constructor is divided into two phases: 1. Initialization Phase 2. Normal computing phase. (The computing phase consists of all the statements in the constructor's function body. Initialization of member variables takes place before the computing phase !!!)
So how do we initialize the member variables?
1. Through the constructor'sInitialization list, Advocate !!
2. Do not use the initialization list: (1). The member variables of the class type are initialized using the default constructor; (2) built-in types: perform global initialization based on the scope of the variable, local Initialization is not performed.
Note:
1. The initialization list of the constructor is specified in the definition of the constructor rather than in the Declaration.
2. Some variables must be initialized using the initialization list: class type variables without Default constructors, const member variables, and reference type variables