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

2014-11-24 13:23:11 · 作者: · 浏览: 31

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

示例:

int x = 0;//对int进行手工初始化
const char *text = A C-style string;  //对指针进行手工初始化

double d;
std::cin >> d;//以读取input stream的方式完成初始化

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

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

#include 
  
   
using namespace std;

class A{
public:
	A(){cout << default constructor << endl;};
	A(int v):value(v){};
	A(const A &a2){cout << copy constructor << endl;}
	const A& operator=(const A &lhr) const{cout << operator= << endl; return *this;}
private:
	int value;
};

class B{
public:
	B(A a2){a = a2;};  //用赋值操作初始化
private:
	A a;
};

int main(){
	A a(1);
	B b(a);  //主要是通过输出看定义b变量调用的函数情况
	system(pause);
}
  

输出1:

copy constructor //调用A的copy constructor为B构造函数生成参数a2

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

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


示例2:使用成员初值列

#include 
  
   
using namespace std;

class A{
public:
	A(){cout << default constructor << endl;};
	A(int v):value(v){};
	A(const A &a2){cout << copy constructor << endl;}
	const A& operator=(const A &lhr) const{cout << operator= << endl; return *this;}
private:
	int value;
};

class B{
public:
	B(A a2):a(a2){};
private:
	A a;
};

int main(){
	A a(1);
	B b(a);
	system(pause);
}
  

输出2:

copy constructor //调用A的copy constructor为B构造函数生成参数a2

copy constructor //调用A的copy constructor将a复制为a2