构造函数初始化列表是对成员变量的初始化,先于构造函数函数体执行。
对于内置函数,初始化列表中初始化和构造函数函数体中初始化没什么区别;
而对于类类型,建议使用初始化列表,因为构造函数函数体中初始化的话,变量多一次复制操作和默认构造的过程。
#include "stdafx.h"
#include <iostream>
using namespace std;
#define USE_INIILIST
class CMemberValue
{
public:
CMemberValue(int i = 0)
:m_i(i)
{
cout << "default constructor" << " m_i = " << m_i << endl;
}
CMemberValue(const CMemberValue &rhs)
{
this->m_i = rhs.m_i;
cout << "copy constructor" << " m_i = " << m_i << endl;
}
CMemberValue &operator=(const CMemberValue &rhs)
{
this->m_i = rhs.m_i;
cout << "assignment operator" << " m_i = " << m_i << endl;
return *this;
}
private:
int m_i;
};
class CTest
{
public:
#ifdef USE_INIILIST
CTest()
:m_MemberValue(10)
{
}
#else
CTest()
{
m_MemberValue = CMemberValue(10);
}
#endif
private:
CMemberValue m_MemberValue;
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest test;
getchar();
return 0;
}
初始化化列表中初始化:
构造函数体中初始化:
参考:http://www.cnblogs.com/graphics/archive/2010/07/04/1770900.html