必须使用初始化列表的几种情况

时间:2020-12-02 19:39:30

必须使用初始化列表的几种情况

1. 类的成员变量有const修饰;
2. 类的成员为引用;
3. 类的成员为没有默认构造函数的类类型;

#include <iostream>
using namespace std;

class Base
{
    public:
        Base(int p_nValue) : m_nValue(p_nValue) {}
    private:
        int m_nValue;
};

class MyClass
{
    public:
        MyClass(int p_nValue) : m_objBase(p_nValue),m_nNewVal(p_nValue) m_nVal(p_nValue) {}
        void printVal() { cout << "hello:" << p << endl;}
    private:
        const int m_nVal;
        int &m_nNewVal;
        Base m_objBase;
};

int main(int argc ,char **argv)
{
    int nValue = 45;
    MyClass objMyClass(nValue );
    objMyClass.printVal();
}

4. 如果类存在继承关系,派生类必须在其初始化列表中调用基类的构造函数;

#include <iostream>
using namespace std;

class Parent
{
    public:
        Parent(int p_nVal) : m_nVal(p_nVal) {}
    private:
        int m_nVal;
};

class Child : public Parent
{
    public:
        Child(int p_nVal) : m_nNewVal(p_nVal), Parent(p_nVal) {}
        void printVal() { cout << "hello:" << p << endl;}
    private:
        int m_nNewVal;
};

int main(int argc ,char **argv)
{
    int nValue = 45;
    Child objChild(nValue);
    objChild.printVal();
}