Article directory
- 1.1 Constructor body assignment:
- 2. Initialization list
-
- 2.1 Initialize the basic form, note:
- 3. Try to use the initialization list to initialize, because whether you use the initialization list or not, for custom type member variables, you must use the initialization list to initialize first.
- 4. The order in which member variables are declared in the class is the order in which they are initialized in the initialization list, regardless of their order in the initialization list
- 三、explicit:
1.1 Constructor body assignment:
When creating an object, the compiler calls the constructor to give each member variable in the object an appropriate initial value.
Although the object already has an initial value after the above constructor is called, it cannot be called the initialization of the member variables in the object. The statement in the constructor body can only be called the initial value assignment, not the initial value . initialization. Because the initialization can only be initialized once, and the constructor body can be assigned multiple times.
2. Initialization list
2.1 Initialize the basic form, note:
Initialization list: Starts with a colon, followed by a comma-separated list of data members, each "member variable" followed by an initial value or expression enclosed in parentheses.
[Note]
1. Each member variable can only appear once in the initialization list (initialization can only be initialized once)
2. The class contains the following members, which must be placed in the initialization list for initialization :
1. Reference member variables
2. const members Variable
3. Custom type member (and when the class has no default constructor)
3. Try to use the initialization list to initialize, because whether you use the initialization list or not, for custom type member variables, you must use the initialization list to initialize first.
4. The order in which member variables are declared in the class is the order in which they are initialized in the initialization list, regardless of their order in the initialization list
三、explicit:
Constructors can not only construct and initialize objects, but also have the function of type conversion for a single parameter or a constructor with default values except for the first parameter .
Adding explicit can prevent implicit type conversion from happening