以下几种情况时必须使用初始化列表:
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