目录
1.内置类型
对于内置类型,在定义的时候就要将其初始化,编译器可能会帮你初始化,但是这并不是C++默认的行为,养成一个好习惯。
int a = 0; //这样
int b; // 不建议这样
2.自定义类型
一定要使用构造函数初始化列表,而不是在构造函数的函数体内赋值。
class ABEntry
{
ABEntry(const std::string& name, const std::string& address)
:_name(name)
,_address(address)
{
}
private:
std::string _name;
std::string _address;
};
// 不要这样
class ABEntry
{
ABEntry(const std::string& name, const std::string& address)
{
_name = name;
_address = address;
}
private:
std::string _name;
std::string _address;
};
成员初始化的顺序,就是类内声明的顺序。
当一个成员变量初始化,需要用到另一个成员变量,要保证初始化的次序。
例:array数组初始需要大小,在array初始化之前 保证表示大小的那个成员已经初始化完毕。
3.static成员
class Diretory
{
public:
Diretory()
{
std::size_t disks = tfs.nums;
// tfs是其他编译单元的静态对象
}
};
Diretory在构造的时候 tfs这个变量可能还没有初始化,因为不同编译单元中变量的初始化次序是不确定的。
可以通过单例模式来解决这个问题。
class FileSystem
{
public:
FileSystem &tfs()
{
static FileSystem fs;
return fs;
}
}
class Diretory
{
public:
Diretory()
{
std::size_t disks = tfs().nums;
// tfs是其他编译单元的静态对象
}
};

被折叠的 条评论
为什么被折叠?



