首页 > 代码库 > 什么时候需要在类的构造函数中使用初始化列表
什么时候需要在类的构造函数中使用初始化列表
1,如果基类没有default构造函数,则意味着其不能自己初始化。如果其被派生,派生类的构造函数要负责调用基类的构造函数,并传递给它需要的参数。下例中Base
2,如果类成员没有默认构造函数。下例中Elem4
2,如果类的成员变量中含有const成员变量,如果不使用列表,在构造函数中是不能对其赋值的,会导致编译失败。下例中b
3,如果类的成员变量中含有引用,引用必须被初始化。下例中c
4,需要提高效率的时候,如果不使用初始化列表,而放在构造函数体内赋值的方法,则变量先被默认构造函数初始化,然后又调用copy构造函数。
1 /////////////////////////////////////////////////////////////////////////////// 2 // 3 // FileName : constructor.h 4 // Version : 0.10 created 2013/11/09 00:00:00 5 // Author : Jimmy Han 6 // Comment : 7 // 8 /////////////////////////////////////////////////////////////////////////////// 9 #include <iostream>10 using namespace std;11 12 class Elem1{13 public:14 Elem1(int x){15 cout << "Elem1() was called." << endl;16 }17 ~Elem1(){18 cout << "~Elem1() was called." << endl;19 }20 };21 22 class Elem2{23 public:24 Elem2(int x){25 cout << "Elem2() was called." << endl;26 }27 ~Elem2(){28 cout << "~Elem2() was called." << endl;29 }30 };31 32 class Elem3{33 public:34 Elem3(int x){35 cout << "Elem3() was called." << endl;36 }37 ~Elem3(){38 cout << "~Elem3() was called." << endl;39 }40 };41 42 class Elem4{43 public:44 Elem4(int x){45 cout << "Elem4() was called." << endl;46 }47 ~Elem4(){48 cout << "~Elem4() was called." << endl;49 }50 };51 52 53 class Base{54 public:55 Base(int):_elem2(Elem2(2)), _elem1(Elem1(1)), _elem3(Elem3(3)){56 cout << "Base() was called." << endl;57 }58 ~Base(){59 cout << "~Base() was called." << endl;60 }61 private:62 Elem1 _elem1;63 Elem2 _elem2;64 Elem3 _elem3;65 };66 67 class Derive : public Base{68 public:69 //if there is no default constructor for base class, it has to be called explicit in derive class70 //four scenarios to use initialization list must:71 //1. Base. base class don‘t have Base();72 //2. const int b. class member is const 73 //3. int& c. class member is reference74 //4. _elem4. class member dont‘ have default constructor.75 Derive():Base(1), _elem4(Elem4(4)), b(3), c(b){76 cout << "Derive() was called." << endl;77 }78 private:79 Elem4 _elem4;80 const int b;81 const int& c;82 83 };
1 /////////////////////////////////////////////////////////////////////////////// 2 // 3 // FileName : constructor_client.cc 4 // Version : 0.10 5 // Author : Ryan Han 6 // Date : 2013/11/19 7 // Comment : 8 // Elem1() was called. 9 // Elem2() was called.10 // Elem3() was called.11 // Base() was called.12 // Elem4() was called.13 // Derive() was called.14 // ~Elem4() was called.15 // ~Base() was called.16 // ~Elem3() was called.17 // ~Elem2() was called.18 // ~Elem1() was called.19 //20 ///////////////////////////////////////////////////////////////////////////////21 #include <iostream>22 #include "constructor.h"23 using namespace std;24 25 int main(){26 Derive d1;27 28 return 0;29 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。