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 initializationsthePhones = 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 initializationsthePhones(phones),numTimesConsulted(0){} // the ctor body is now empty
這是初始化列表?
局部靜態對象的的初始化順序
在不同的文件中 在一個文件中使用另一個文件的局部靜態變量? 可能會未進行初始化
這可能是由于文件的位置不同
class FileSystem { ... }; // as beforeFileSystem& tfs() // this replaces the tfs object; it could be
{ // static in the FileSystem classstatic FileSystem fs; // define and initialize a local static objectreturn fs; // return a reference to it
}class Directory { ... }; // as beforeDirectory::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 classstatic Directory td; // define/initialize local static objectreturn td; // return reference to it
}
手動初始化 內建類型的對象,因為 C++ 只在某些時候才會自己初始化它們。
在 構造函數中,用成員初始化列表代替函數體中的 賦值。初始化列表中 數據成員的排列順序要與它們在類中被聲明的順序相同。
通過用局部靜態對象代替 非局部靜態對象來避免跨轉換單元的 初始化順序問題。