确定对象使用前已先被初始化
我们都明白如果程序中使用了未经初始化的数据成员,那么程序将会出现非预期的错误结果。
本节就是说明如何初始化的一般方法
首先
对于一个class来说,它的初始化使用成员初始化列进行,构造函数中所谓的“初始化”是赋值。如下,前者是初始化后赋值,后者是直接初始化。
class P{
public:
P(int x0, int y0)
{
x=x0;
y=y0;
}
private:
int x,y;
}
class P{
public:
P(int x0, int y0):x(x0),y(y0)
{
x=x0;
y=y0;
}
private:
int x,y;
}
接着
对于non-local staitic对象,由于不确定该对象是否初始化,所以,每次使用时,直接重新定义并初始化:
class FileSystem{
public:
……
std::size_t numDisks()const;
……
};
FileSystem& tfs()
{
static FileSystem fs;
return fs;
}
class Directory{
public:
Directory( params )
{
……
std::size_t disks=tfs.numDisks();
……
}
};
Directory tempDir()
{
static Directory td;
return td;
}