Effective C++ Item 4 确定对象被使用前已先被初始化

来源:互联网 发布:recyclerview如何优化 编辑:程序博客网 时间:2024/05/14 22:24

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


经验1:为内置对象进行手工初始化,因为C++不保证初始化它们

示例:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. int x = 0;//对int进行手工初始化  
  2. const char *text = "A C-style string";  //对指针进行手工初始化  
  3.   
  4. double d;  
  5. std::cin >> d;//以读取input stream的方式完成初始化  


经验2:构造函数最好使用成员初值列 (member initialization list) ,而不要在构造函数本体内使用赋值操作(assignment) 。初值列列出的成员变量,其排列次序应该和它们在 class 中的声明次序相同。

示例1:用赋值操作初始化

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class A{  
  5. public:  
  6.     A(){cout << "default constructor" << endl;};  
  7.     A(int v):value(v){};  
  8.     A(const A &a2){cout << "copy constructor" << endl;}  
  9.     const A& operator=(const A &lhr) const{cout << "operator=" << endl; return *this;}  
  10. private:  
  11.     int value;  
  12. };  
  13.   
  14. class B{  
  15. public:  
  16.     B(A a2){a = a2;};  //用赋值操作初始化  
  17. private:  
  18.     A a;  
  19. };  
  20.   
  21. int main(){  
  22.     A a(1);  
  23.     B b(a);  //主要是通过输出看定义b变量调用的函数情况  
  24.     system("pause");  
  25. }  

输出1:

copy constructor      //调用Acopy constructorB构造函数生成参数a2

default constructor    //进入B的构造函数前调用A的默认构造函数定义a

operator=               //调用赋值操作符将a赋值为a2


示例2:使用成员初值列

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class A{  
  5. public:  
  6.     A(){cout << "default constructor" << endl;};  
  7.     A(int v):value(v){};  
  8.     A(const A &a2){cout << "copy constructor" << endl;}  
  9.     const A& operator=(const A &lhr) const{cout << "operator=" << endl; return *this;}  
  10. private:  
  11.     int value;  
  12. };  
  13.   
  14. class B{  
  15. public:  
  16.     B(A a2):a(a2){};  
  17. private:  
  18.     A a;  
  19. };  
  20.   
  21. int main(){  
  22.     A a(1);  
  23.     B b(a);  
  24.     system("pause");  
  25. }  

输出2:

copy constructor              //调用Acopy constructorB构造函数生成参数a2

copy constructor              //调用Acopy constructora复制为a2

0 0
原创粉丝点击