C++ 初始化列表

初始化列表顾名思义就是在初始化对象的时候初始化列表中的成员, 要与成员赋值区分开来. 初始化列表的特殊用途:

  • 初始化const成员.
  • 初始化引用成员.
  • 初始化没有默认构造函数的对象或父类.

下面看一个例子:

#include <iostream>

class base {
    const int m_a;

  public:
    base(int a) : m_a(a) {}
    void show(void) { std::cout << "base m_a: " << m_a << std::endl; }
};

class derived : public base {
    const int m_a;
    int &m_b;

  public:
    derived(int a, int &b) : m_a(a), m_b(b), base(a + 1) {}

    void show(void) {
        std::cout << "derived m_a: " << m_a << std::endl;
        std::cout << "derived m_b: " << m_b << std::endl;
    }

    void show_base(void) { base::show(); }
};

int main(void) {
    int b = 2;
    derived d{1, b};
    d.show(); // 输出: derived m_a: 1; derived m_b: 2
    d.show_base(); // 输出: base m_a: 2
}

如果觉得有帮助,可以扫描右边的微信打赏码支持一下.

Leave a Reply

Your email address will not be published. Required fields are marked *