fun(){
int a;
printf("%d\n", a);
cout << a << endl;
//会报错 使用了未初始化的变量a
}
//若a是全局变量则不会报错 会默认初始化为0
在对象中优先使用初始化列表:
ABEntry::ABEntry(const std::string& name, const std::string& address,
const std::list<PhoneNumber>& phones)
{
theName = name; // these are all assignments,
theAddress = address; // not initializations
thePhones = phones;
numTimesConsulted = 0;
}
这样是没有使用初始化列表 在调构造函数之前会对这个对象的成员进行默认的初始化,再到构造函数当中 去进行赋值, 所以这里是进行的赋值操作并不是初始化。
ABEntry::ABEntry(const std::string& name, const std::string& address,
const std::list<PhoneNumber>& phones)
: theName(name),
theAddress(address), // these are now all initializations
thePhones(phones),
numTimesConsulted(0)
{} // the ctor body is now empty
这是初始化列表
局部静态对象的的初始化顺序
在不同的文件中 在一个文件中使用另一个文件的局部静态变量 可能会未进行初始化
这可能是由于文件的位置不同
class FileSystem { ... }; // as before
FileSystem& tfs() // this replaces the tfs object; it could be
{ // static in the FileSystem class
static FileSystem fs; // define and initialize a local static object
return fs; // return a reference to it
}
class Directory { ... }; // as before
Directory::Directory( params ) // as before, except references to tfs are
{ // now to tfs()
...
std::size_t disks = tfs().numDisks();
...
}
Directory& tempDir() // this replaces the tempDir object; it
{ // could be static in the Directory class
static Directory td; // define/initialize local static object
return td; // return reference to it
}
手动初始化 内建类型的对象,因为 C++ 只在某些时候才会自己初始化它们。
在 构造函数中,用成员初始化列表代替函数体中的 赋值。初始化列表中 数据成员的排列顺序要与它们在类中被声明的顺序相同。
通过用局部静态对象代替 非局部静态对象来避免跨转换单元的 初始化顺序问题。