为内置对象进行手工初始化,C++不保证初始化它们
确保每一个构造函数都将对象的每一个成员初始化。
#include <iostream>
using namespace std;
#include <string>
class Test {
public:
Test(const string &str, const string& add, int num)
{
name = str; //这些都是赋值,非初始化,初始化发生在函数体之前
theaddress = add;
number = num;
}
private:
string name;
string theaddress;
int number;
};
这种写法会调用default的构造函数为成员初始化,然后立刻赋值,虽然得到结果正确,但是效率不如下面的。
Test(const string &str, const string& add, int num)
:name(str)
,theaddress(add)
,number(num)
{}
无参的构造函数初始化
Test()
:name()
,theaddress()
,number(0)
{}
const成员和reference一定得在初始化列表中完成,base class总是早于derived class被初始化。 class成员总是以成员声明的顺序初始化。
- 不同编译单元内定义的non_local static对象初始化次序。
static对象,其寿命从被构造函数直到程序结束为止。(heap, stack对象被除)。包括global对象,namespace作用域内的对象,还有函数类内,file作用域中,class中被声明为static对象被称为 static对象。函数内的static对象称为local-static对象。 其他的称为static对象称为non-local static对象。
如果有两个源文件,每一至少含有一个non-local static对象。
class FileSystem //程序库
{
...
size_t numDisks() const;
...
};
extern FileSystem tfs; //预备给客户使用的对象
C++中对于定义在不同编译单元内的non-local static对象的初始化次序没有明确定义。而客户端如果使用tfs对象。可能tfs还没有初始化,就可能发生错误。Director temp(tfs.numDisks()) // 可户用tfs的函数初始化自己的目录,但是tfs可能还没有初始化
解决方法:
FileSystem &tfs()
{
static FileSystem fs;
return fs;
}
用local static 对象代替 non-local static对象。如果使用频繁可以设为inline函数。这样就可以解决non-local static对象的初始化顺序问题。