C++类构造函数中的成员初始化

成员初始化列表,形式如下(在参数列表后面以冒号为起点,之后是一个初始化列表):

Rectangle::Rectangle (int x, int y) : width(x), height(y) { }

 

关于构造函数、以及成员初始化列表的细节,见[1]。

这里摘出比较关键的两段话:

For members of fundamental types, it makes no difference which of the ways above the constructor is defined, because they are not initialized by default, but for member objects (those whose type is a class), if they are not initialized after the colon, they are default-constructed.
对于基本类型(int, float, bool)等,用不用成员初始化列表没有差异;而对于对象(基于类, class),如果没有进初始化列表,在执行构造函数函数体前,会对其进行缺省构造。

Default-constructing all members of a class may or may always not be convenient: in some cases, this is a waste (when the member is then reinitialized otherwise in the constructor), but in some other cases, default-construction is not even possible (when the class does not have a default constructor). In these cases, members shall be initialized in the member initialization list. 

在相当一部分情况下,进行缺省构造是不合理的行为。这也正是成员初始化列表存在的意义所在。

 

参考:

[1]http://www.cplusplus.com/doc/tutorial/classes/

转载于:https://www.cnblogs.com/wuzhenwei/p/4566469.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值