c++基础之类内初始化

本文探讨了C++11引入的类内初始器如何减少构造函数中的重复初始化代码,通过展示代码示例,说明了如何使用类内初始化使构造函数更加简洁,提高代码可读性和维护性。

重复的初始化代码

考察下面的代码:

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

};

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值