[C ++ in-depth analysis learning summary] 20 Use of initialization list
Author CodeAllen , please indicate the source
Can const members be defined in a class?
can
Are the following class definitions legal?
illegal
Const members in the class
#include <stdio.h>
class Test
{
private:
const int ci;
public:
Test() : ci(10)
{
//ci = 10; //这里编译会出错的
}
int getCI()
{
return ci;
}
};
int main()
{
Test t;
printf("t.ci = %d\n", t.getCI());
return 0;
}
1. Initialization of class members
C ++ provides an initialization list to initialize member variables
Syntax rules
Precautions
- The initialization order of members is the same as the declaration order of members (prone to bugs)
- The initialization order of members is independent of the position in the initialization list
- The initialization list is executed before the function body of the constructor
Use of initialization list
class Test
{
private:
value m2;
value m3;
value m1;
public:
Test() : m1(1),m2(2),m(3)
{
}
};
输出: 2 3 1 和声明顺序相同
2. Const members in the class
- Const members in the class will be allocated space
- The essence of const members in a class is read-only variables
- Const members in the class can only specify initial values in the initialization list
- The compiler cannot directly get the initial value of the const member, so it cannot enter the symbol table to become a constant in the true sense.
Initialization and assignment are different
- Initialization: Initial value setting for the object being created
- Assignment: set the value of an existing object
Summary
You can use the initialization list to initialize members in the class. The initialization list
is executed before the constructor body
. The const member variable can be defined in the class. The
const member variable must specify the initial value in the initialization list. The
const member variable is read-only.