初始化列表
作用:
C++提供了初始化列表语法,用来初始化属性
语法:构造函数():属性1(值1),属性2(值2).....{}
先介绍一下传统的初始化操作:
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 test01()
{
Person p(10, 20, 30);
cout << "m_A= " << p.m_A << endl;
cout << "m_B= " << p.m_B << endl;
cout << "m_C= " << p.m_C << endl;
}
int main()
{
test01();
return 0;
}
使用初始化列表初始化属性:
class Person
{
public:
//初始化列表初始化属性
Person() :m_A(10), m_B(20), m_C(30)
{
}
int m_A;
int m_B;
int m_C;
};
void test01()
{
Person p;
cout << "m_A= " << p.m_A << endl;
cout << "m_B= " << p.m_B << endl;
cout << "m_C= " << p.m_C << endl;
}
int main()
{
test01();
return 0;
}
但是使用这个方法m_A,m_B,m_B的值是固定的,我们可以修改代码使得它们的值变得灵活:
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 test01()
{
Person p(10, 20, 30);
cout << "m_A= " << p.m_A << endl;
cout << "m_B= " << p.m_B << endl;
cout << "m_C= " << p.m_C << endl;
}
int main()
{
test01();
return 0;
}
这三个代码的输出结果都是下图:
![](https://i-blog.csdnimg.cn/blog_migrate/fe0f6cb4a7d34be04167025220f4fd18.png)