哪些東西必須放在構造函數的初始化列表中?

以下幾種情況時必須使用初始化列表:

1 常量成員,因爲常量只能初始化不能賦值,所以必須放在初始化列表裏面

2 引用類型,引用必須在定義的時候初始化,並且不能重新賦值,所以也要寫在初始化列表裏面

3 沒有默認構造函數的類類型,因爲使用初始化列表可以不必調用默認構造函數來初始化,而是直接調用拷貝構造函數初始化。


針對上面3種情況,寫代碼測試結果如下:

class CBase
{
public:
    CBase(int i, int j, int k, int &r):m_i(i), m_j(j), m_k(k), m_r(r)
    {
        //m_k = k; // error, compiler report that must be initialized in initializer list
        //m_r = r; // error, same reason as above
    };
protected:
private:
    int m_i;
    int m_j;
    const int m_k;  // const member
    int &m_r;       // reference member
};

class CSecond
{
public:
    CSecond(CBase base):m_base(base) // that is ok!
    {
        //m_base = base; // error, no appropriate default constructor available
    };
private:
    CBase m_base;
};

int _tmain(int argc, _TCHAR* argv[])
{
    int nNum = 4;
    //CBase base; // error, if Class provide a construct with argument, 
                  // there have no default construct without argument 
    CBase base(1, 2, 3, nNum);

	return 0;
}

參考文章:http://www.cnblogs.com/graphics/archive/2010/07/04/1770900.html

發佈了49 篇原創文章 · 獲贊 71 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章