C++11类内初始化怎么实现

发布时间:2021-11-26 14:33:45 作者:iii
来源:亿速云 阅读:151

本篇内容主要讲解“C++11类内初始化怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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};   

};

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

到此,相信大家对“C++11类内初始化怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. 总结C++11中decltype、类内初始化、列表初始化返回值
  2. C++11如何统一初始化

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++11类型别名和typedef有什么区别

下一篇:C#如何实现基于Socket套接字的网络通信封装

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》