[C++] Features and precautions of constructor initialization list


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.
insert image description here

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.
insert image description here
[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)
insert image description here

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

insert image description here

三、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 .

insert image description here

Adding explicit can prevent implicit type conversion from happening
insert image description here

Guess you like

Origin blog.csdn.net/m0_74774759/article/details/130910359