在C++ 中 , 有兩種初始化的方式 , 分別是explicit initialization 與implicit initialization.

intnValue = 5; // explicit assignment

intnValue(5); // implicit assignment

而如果在我們所定義的class中 , 我們想要初始化這個class裡面的一些data member , 通常我們會使用下面的方式:

 

class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;
public:
    Something()
    {
        m_nValue = 0;
        m_dValue = 0.0;
        m_pnValue = 0;
    }
};

但是如果class裡面的private data member 其type 是const 或reference , 則這樣的方式將會導致compile error , 
因為在C++中 , const與reference必須在一開始就initialize , const必須要指定一個值給他 , 
而reference則要去reference something , 且reference不能redirect(即不能改變他reference的對象.)

class Something
{
private:
    const int m_nValue;   //no initialization value.
public:
    Something()
    {
        m_nValue = 5;
    }
};

在上面這個例子中 , 在我們宣告 const int m_nValue時 , compiler此時便會進行初始化 , 發現並無指定一個值給m_nValue , 
便會發生error.
(若是class , compiler則會呼叫default constructor進行初始化 , 我們也可以想成const是呼叫default constructor來進行初始化.)

所以此時我們應該使用implicit initialization的方式 , 也就是Constructor initialization list , 
藉由Contructor initialization list , 會取代掉宣告時所呼叫的default constructor , 而改以initialization list
中的contructor來進行implicit assignment.

class Something
{
private:
    const int m_nValue;
public:
    Something(): m_nValue(5)
    {
    }
};

我們可以進一步的初始化 :
class CMyClass 
CMyClass(int x, int y); 
int m_x; int m_y; 
}; 
CMyClass::CMyClass(int i) : m_y(i), m_x(m_y) { }


 

 

 

ref : http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/

       http://www.cprogramming.com/tutorial/initialization-lists-c++.html

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()