C++-什么时候需要在类的构造函数中使用初始化列表

1,如果基类没有default构造函数,则意味着其不能自己初始化。如果其被派生,派生类的构造函数要负责调用基类的构造函数,并传递给它需要的参数。下例中Base

2,如果类成员没有默认构造函数。下例中Elem4

2,如果类的成员变量中含有const成员变量,如果不使用列表,在构造函数中是不能对其赋值的,会导致编译失败。下例中b

3,如果类的成员变量中含有引用,引用必须被初始化。下例中c

4,需要提高效率的时候,如果不使用初始化列表,而放在构造函数体内赋值的方法,则变量先被默认构造函数初始化,然后又调用copy构造函数。

 ///////////////////////////////////////////////////////////////////////////////
//
// FileName : constructor.h
// Version : 0.10 created 2013/11/09 00:00:00
// Author : Jimmy Han
// Comment :
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
using namespace std; class Elem1{
public:
Elem1(int x){
cout << "Elem1() was called." << endl;
}
~Elem1(){
cout << "~Elem1() was called." << endl;
}
}; class Elem2{
public:
Elem2(int x){
cout << "Elem2() was called." << endl;
}
~Elem2(){
cout << "~Elem2() was called." << endl;
}
}; class Elem3{
public:
Elem3(int x){
cout << "Elem3() was called." << endl;
}
~Elem3(){
cout << "~Elem3() was called." << endl;
}
}; class Elem4{
public:
Elem4(int x){
cout << "Elem4() was called." << endl;
}
~Elem4(){
cout << "~Elem4() was called." << endl;
}
}; class Base{
public:
Base(int):_elem2(Elem2()), _elem1(Elem1()), _elem3(Elem3()){
cout << "Base() was called." << endl;
}
~Base(){
cout << "~Base() was called." << endl;
}
private:
Elem1 _elem1;
Elem2 _elem2;
Elem3 _elem3;
}; class Derive : public Base{
public:
//if there is no default constructor for base class, it has to be called explicit in derive class
//four scenarios to use initialization list must:
//1. Base. base class don't have Base();
//2. const int b. class member is const
//3. int& c. class member is reference
//4. _elem4. class member dont' have default constructor.
Derive():Base(), _elem4(Elem4()), b(), c(b){
cout << "Derive() was called." << endl;
}
private:
Elem4 _elem4;
const int b;
const int& c; };
 ///////////////////////////////////////////////////////////////////////////////
//
// FileName : constructor_client.cc
// Version : 0.10
// Author : Ryan Han
// Date : 2013/11/19
// Comment :
// Elem1() was called.
// Elem2() was called.
// Elem3() was called.
// Base() was called.
// Elem4() was called.
// Derive() was called.
// ~Elem4() was called.
// ~Base() was called.
// ~Elem3() was called.
// ~Elem2() was called.
// ~Elem1() was called.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "constructor.h"
using namespace std; int main(){
Derive d1; return ;
}
上一篇:Javascript的千分位和去除千分位


下一篇:C++类的成员初始化列表的相关问题