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;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凉开水白菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值