初始化列表操作实际上就是构造函数在初始化成员时的一个语法糖。
例如传统方法初始化:
#include <iostream>
#include <string>
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;
};
void Example() {
Person p1(10, 20, 30);
cout << "m_a = " << p1.m_a << endl;
cout << "m_b = " << p1.m_b << endl;
cout << "m_c = " << p1.m_c << endl;
}
int main()
{
Example();
return 0;
}
列表化:简化后的
#include <iostream>
#include <string>
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;
};
void Example() {
Person p1;
cout << "m_a = " << p1.m_a << endl;
cout << "m_b = " << p1.m_b << endl;
cout << "m_c = " << p1.m_c << endl;
}
int main()
{
Example();
return 0;
}
或者赋值的形式可以写成
#include <iostream>
#include <string>
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;
};
void Example() {
Person p1(10,20,30);
cout << "m_a = " << p1.m_a << endl;
cout << "m_b = " << p1.m_b << endl;
cout << "m_c = " << p1.m_c << endl;
}
int main()
{
Example();
return 0;
}