c++11:类内初始化

 

类内初始化

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值