失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > C++类构造函数中的成员初始化

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

时间:2022-10-26 04:33:31

相关推荐

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]/doc/tutorial/classes/

如果觉得《C++类构造函数中的成员初始化》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。