1. 对象使用之前进行初始化
void Test00() { int x = 0; const char* text = "A C-style string"; double d; std::cin >> d; }
1. 使用初始化列表进行初始化
2. baseClass的初始化早于derivedClass
3. class的成员变量总是以声明的顺序进行初始化,而不是在成员初值列中的顺序
class PhoneNumber {}; class ABEntry { public: ABEntry() : theName(), theAddress(), thePhones(), numTimesConsulted(0) {} ABEntry(const std::string& name, const std::string& address, const std::list<PhoneNumber>& phones) : theName(name), theAddress(address), thePhones(phones),numTimesConsulted(0) {} private: std::string theName; std::string theAddress; std::list<PhoneNumber> thePhones; int numTimesConsulted; };
1. 初始化次序的重要性,tfs在tempDir之前先被初始化,否则tempDir的构造函数会用到尚未初始化的tfs
2. 定义并初始化一个local static对象,以免除"跨编译单元之初始化次序"
class FileSystem { public: size_t numDisks() { return 1u; } }; FileSystem& tfs() { static FileSystem fs; return fs; } class Directory { public: Directory() { std::size_t disks = tfs().numDisks(); } }; Directory& tempDir() { static Directory td; return td; }
标签:std,初始化,const,string,04,Directory,class,条款 From: https://www.cnblogs.com/BoYuCG/p/18402129