列表赋值:如果成员为const类型或者是引用类型(&)则可以使用该方法给成员赋初值。
// 类列表初始化
class Person
{
public:
// 直接复制传给成员
Person(int _x, int _y);
// 列表方式
Person(int _x, int _y, int _z) : m_x(_x), m_y(_y), m_z(_z)
{
// 如果私有成员是const或者引用类型的时候就需要使用列表初始化方式构造
cout << "使用列表方式初始化";
}
private:
int m_x;
int m_y;
const int m_z = 0;
};
完整示例
#include <iostream>
using namespace std;
#include <vector>
// 类列表初始化
class Person
{
public:
// 直接复制传给成员
Person(int _x, int _y);
// 列表方式
Person(int _x, int _y, int _z) : m_x(_x), m_y(_y), m_z(_z)
{
// 如果私有成员是const或者引用类型的时候就需要使用列表初始化方式构造
cout << "使用列表方式初始化";
}
vector<int> printPerson()
{
vector<int> temp;
temp.push_back(this->m_x);
temp.push_back(this->m_y);
temp.push_back(this->m_z);
return temp;
}
private:
int m_x;
int m_y;
const int m_z = 0;
};
Person::Person(int _x, int _y)
{
this->m_x = _x;
this->m_y = _y;
cout << "使用直接赋值方式";
};
ostream &operator<<(ostream &out, Person &p)
{
vector<int> temp = p.printPerson();
for (auto it = temp.begin(); it != temp.end(); it++)
{
out << *it << " ";
}
out << endl;
return out;
}
int main(int argc, char **argv)
{
Person p1(10, 1900, 190);
cout << p1;
Person p2(10, 111);
cout << p2;
return 0;
}