作用

C++提供了初始化列表语法,用来初始化属性

语法

构造函数(参数): 属性1(值1),属性2(值2)...{函数体}

示例:

传统初始化操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;

class Person{
public:

Person(int a, int b, int c) {
m_A = a;
m_B = b;
m_C = c;
}

int m_A;
int m_B;
int m_C;
};


int main() {
Person p(10, 20, 30);
cout << "m_A=" << p.m_A << endl << "m_B=" << p.m_B << endl<< "m_C=" << p.m_C << endl;
return 0;
}

初始化列表方式初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;

class Person{
public:

Person() :m_A(10),m_B(20),m_C(30) {

}

int m_A;
int m_B;
int m_C;
};


int main() {
Person p;
cout << "m_A=" << p.m_A << endl << "m_B=" << p.m_B << endl<< "m_C=" << p.m_C << endl;
return 0;
}

上列代码中m_A、B、C的值已经无法更改,为了让这些值更灵活的传入

可以这样写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
using namespace std;

class Person{
public:

Person(int a, int b, int c) :m_A(a),m_B(b),m_C(c) {

}

int m_A;
int m_B;
int m_C;
};


int main() {
Person p(20,30,10);
cout << "m_A=" << p.m_A << endl << "m_B=" << p.m_B << endl<< "m_C=" << p.m_C << endl;
return 0;
}