C++在构造函数中如何给const成员赋值

简介: C++在构造函数中如何给const成员赋值

列表赋值:如果成员为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;
}


相关文章
|
21小时前
|
编译器 C语言 C++
从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)(下)
从C语言到C++⑤(第二章_类和对象_中篇)(6个默认成员函数+运算符重载+const成员)
4 1
|
1天前
|
编译器 C++
C++程序中的对象赋值和复制
C++程序中的对象赋值和复制
7 1
|
1天前
|
C++
C++程序中的赋值运算符
C++程序中的赋值运算符
10 2
|
1天前
|
C++
C++程序中的派生类成员访问属性
C++程序中的派生类成员访问属性
9 1
|
1天前
|
编译器 C++
C++程序中的派生类构造函数
C++程序中的派生类构造函数
5 1
|
1天前
|
C++
C++程序中对象成员的引用
C++程序中对象成员的引用
7 2
|
6天前
|
C++ Linux
|
6天前
|
编译器 C++
【C++从练气到飞升】03---构造函数和析构函数
【C++从练气到飞升】03---构造函数和析构函数
|
6天前
|
编译器 C++
【C++】类与对象(运算符重载、const成员、取地址重载)
【C++】类与对象(运算符重载、const成员、取地址重载)
15 2