一点小总结,对于类成员,最好是放在初始化列表里进行初始化,优点如下:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
class Class1
{
public:
int m_iValue;
Class1()// 无参构造函数
{
std::cout << "Construct Class1" << std::endl;
}
Class1(const Class1 &class1)// 拷贝构造函数
{
std::cout << "Copy constructor Class1" << std::endl;
this->m_iValue = class1.m_iValue;
}
Class1& operator = (const Class1 &class1)// 赋值运算符
{
std::cout << "operator = Class1" << std::endl;
this->m_iValue = class1.m_iValue;
return *this;
}
Class1& operator ()(const Class1 &class1)// 赋值运算符
{
std::cout << "operator () Class1" << std::endl;
this->m_iValue = class1.m_iValue;
return *this;
}
};
class Class2
{
public:
Class1 m_class1;
Class2(Class1 &class1)
: m_class1(class1)
{
std::cout << "Construct Class2" << std::endl;
}
};
class Class3
{
public:
Class1 m_class1;
Class3(Class1 &class1)
{
m_class1(class1);
std::cout << "Construct Class3" << std::endl;
}
};
class Class4
{
public:
Class1 m_class1;
Class4(Class1 &class1)
{
m_class1 = class1;
std::cout << "Construct Class4" << std::endl;
}
};
Class1 c1 ;
std::cout << "======================" << std::endl;
Class2 c2(c1) ;
std::cout << "======================" << std::endl;
Class3 c3(c1) ;
std::cout << "======================" << std::endl;
Class4 c4(c1) ;
getchar();
return 0;
}
Class2的成员是在初始化列表里进行初始化,而Class3和Class4的成员是在构造函数里进行直接初始化或者赋值初始化
从运行结果来看,Class2与Class3和Class4少调用了一次Class1的构造函数,当Class1的类对象比较大时,初始化列表
的优点就充分体现出来,另外,像常量成员和引用类型对象必须在初始化列表里进行初始化