一、内置数据类型 在被使用前 应该先被初始化
//定义变量时直接进行初始化
int x = 0;//直接在定义int型变量时 初始化为0
const char* text = "A C-style string!";//在定义C类型的 字符串时直接进行初始化
//通过读取input stream(输入流) 的方式来完成初始化
double b;
cin >> b;
二、自定义数据类型 在被使用前 应该先被初始化
正确示范:
(Effective C++ 推荐我们 写类的构造函数时都用成员初始化列表member initialization list 来初始化成员属性,这是一种高效的做法!)
class PhoneNumber {...};
class ABEntry
{
public:
ABEntry(const string & name, const string& address, const list<PhoneNumber>& phones);
private:
string theName;
string theAddress;
list<PhoneNumber> thePhones;
int numTimesConsulted;
};
ABEntry::ABEntry(const string & name, const string& address, const list<PhoneNumber>& phones)
:theName(name), theAddress(address), thePhones(phones), numTimesConsulted(0){}
但此时可能你会对赋值和初始化操作产生疑惑,不妨再来看以下代码:
//重写构造函数(用给各个成员属性赋值的方式)
ABEntry::ABEntry(const string & name, const string& address, const list<PhoneNumber>& phones)
{
theName = name;
theAddress = address;
thePhones = phones;
numTimesConsulted = 0;
}
这即是assignment赋值操作。这样做会导致ABEntry对象会带有你期望(你指定)的值,但不是最佳做法。C++规定,对象的成员变量(成员属性)的初始化动作是发生在进入构造函数本体之前的。在ABEntry的构造函数内,theName,theAddress,thePhones都不是被初始化,而是被赋值。初始化的发生时间会更早,发生于这些成员的default构造函数(默认构造)被系统自动调用之时(比进入ABEntry有参构造函数本体的时间更早)。但这对numTimesConsulted不为真,因为它是内置数据类型,不保证一定在你所看到的那个赋值动作的时间点之前就获得初值了。
因此构造函数的较佳写法即是:用所谓的成员初始化列表member initialization list 来替换赋值动作!
三、对于“不同编译单元内定义之non-local-static对象的初始化序列”问题,请以 local static 对象来替换non-local static 对象
未完待续。。。