类内初始化
在C++11,我么可以为类内成员变量提供一个初始值,则我们在创建对象的时候,这个初始值就用来初始化该成员变量。
enum LineStyle{
lsSolid,
lsDash,
lsDot,
};
class Rect
{
public:
Rect() :left{0}, top{0}, right{0}, bottom{0},style{lsSolid}
{ }
Rect(int l, int t, int r, int b)
:left{l}, top{t}, right{r}, bottom{b},style{lsSolid}
{ }
Rect(int l, int t, int r, int b, LineStyle ls)
:left{l}, top{t}, right{r}, bottom{b},style{ls}
{ }
private:
int top;
int left;
int right;
int bottom;
LineStyle style;
};
这算是正常不过的代码,但是有一个不算是问题的问题:初期值为缺省值的数据包成员也需要在构造函数里指定,感觉不好。
C++11中引入了类内初始化器,以减少构造函数和初始化代码的数量。
class Rect
{
public:
Rect(int l, int t, int r, int b)
:left{l}, top{t}, right{r}, bottom{b}
{ }
Rect(int l, int t, int r, int b, LineStyle ls)
:left{l}, top{t}, right{r}, bottom{b},style{ls}
{ }
private:
int top{0};
int left{0};
int right{0};
int bottom{0};
LineStyle style{lsSolid};
};
类内初始化之后,构造函数只需要负责和缺省值不同的部分就好,代码精炼很多了。