C/C++编程:类内初始化

1059 篇文章 288 订阅

引入

考察下面的代码:

enum LineStyle{
    isSolid,
    isDash,
    isDot,
};

class Rect{
public:
    Rect() : left{0}, top{0}, right{0}, bottom{0}, style{isSolid}{

    }
    Rect(int l, int t, int r, int b) : left{l}, top{t}, right{t}, bottom{b}, style{isSolid}{

    }
    Rect(int l, int t, int r, int b, LineStyle ls) : left{l}, top{t}, right{t}, bottom{b}, style{ls}{

    }
private:
    int top, left, right, bottom;
    LineStyle style;
};

这算是再正常不过的代码,但是有一个不算问题的问题:初期值为缺省值的数据包成员也需要在构造函数里指定,这样不好。

因此C++11中引入了类内初始化器:以减少构造函数和初始化代码的数量

enum LineStyle{
    isSolid,
    isDash,
    isDot,
};

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}, left{0}, right{0}, bottom{0};
    LineStyle style{isSolid};
};

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

()不能用于类内成员初始化

我们可以在类内声明中为非static数据成员指定初始化器:

class A{
public:
	int a {77};
	int b = 77;
};

出于语法分析和名字查找相关的技术原因,{}和=语法能用于类内成员初始化器,但是()语法就不行

默认情况下,构造函数会使用这种类内初始化器,因此上面等价于:

class A{
public:
	int a ;
	int b;
	A(): a{77}, b{77}{}
};

注意

  • 如果一个成员即被类内初始化,又被构造函数初始化。那么构造函数初始化将“覆盖”默认值
  • 不要令成员初始化依赖于全局函数
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值