重复的初始化代码
考察下面的代码:
enum LineStyle{
lsSolid,
lsDash,
lsDot,
};
class Rect
{
public:
Rect()
:left{0}, top{0}, right{0}, bottom{}
,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};
};
类内初始化之后,构造函数只需要负责和缺省值不同的部分就好,代码精炼很多了。
本文探讨了C++11引入的类内初始器如何减少构造函数中的重复初始化代码,通过展示代码示例,说明了如何使用类内初始化使构造函数更加简洁,提高代码可读性和维护性。

1663

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



