C++11新特性(8)- 类内初始化

重复的初始化代码


考察下面的代码:


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};    

};


类内初始化之后,构造函数只需要负责和缺省值不同的部分就好,代码精炼很多了。


作者观点


有人说,改善都是懒人发起的,作者认为:有一部改善应该是强迫症发起的。


觉得本文有帮助?请分享给更多人。
阅读更多更新文章,请扫描下面二维码,关注微信公众号【面向对象思考】

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/79902405