语法:构造函数():属性1(值1),属性2(值2)...{}
#include<iostream>
#include<cstring>
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 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();
}
#include<iostream>
#include<cstring>
using namespace std;
class Person
{
public:
//传统初始化操作
/*Person(int a, int b, int c)
{
m_A = a;
m_B = b;
m_C = c;
}*/
//初始化列表
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();
}
上面这个缺点是初始化之后无法改变参数
然后下面这个进行优化
#include<iostream>
#include<cstring>
using namespace std;
class Person
{
public:
//传统初始化操作
/*Person(int a, int b, int c)
{
m_A = a;
m_B = b;
m_C = c;
}*/
//初始化列表
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();
}