成员初始化列表,形式如下(在参数列表后面以冒号为起点,之后是一个初始化列表):
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/