更多课程 选择中心

C/C++培训
达内IT学院

400-111-8989

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

  • 发布:薛卫国
  • 来源:面向对象思考
  • 时间:2017-11-14 16:16

重复的初始化代码

考察下面的代码:

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++编程系列之: 多个文件篇
下一篇:Python 扩展使用 C/C++ 给 Python 写扩展模块的方法

超全的C语言标识符知识

C指针——指针类型转换

C指针——指针和结构类型的关系

C指针——数组和指针的关系

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

  • 搜索抖音号

    搜索抖音号:1821685962

    免费领取达内课程视频学习资料

Copyright © 2021 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省