< C++ > initializer list 初始化列表(构造函数后面加个冒号的解释)

Keypoint : 调用父类的构造函数(一般为有参构造函数),初始化类中的成员。


http://zhidao.baidu.com/link?url=N96OhNn11PxhkTNk7SCmd-2g3nrmKv-CtfjMKObGWo15eurHVS9Un03jwkP5BC5xErOXpTbgVHmEL3GBsV_8s_

http://zhidao.baidu.com/link?url=KkbSv_fAwmR-RVvp8KfZQyxyPaG4PlHKmLyTNpabEV82bX5Sw7OKqjf0LLvbXpDGN1mCuyHas-8APxMv5NJp4a

C++ primer 5th edition:

Remember
When creating an object of a derived class, a program first calls the base-class constructor and then
calls the derived-class constructor. The base-class constructor is responsible for initializing the inher-
ited data members. The derived-class constructor is responsible for initializing any added data mem-
bers. A derived-class constructor always calls a base-class constructor. You can use the initializer list
syntax to indicate which base-class constructor to use. Otherwise, the default base-class constructor
is used.


When an object of a derived class expires, the program first calls the derived-class destructor and
then calls the base-class destructor.


Member Initializer Lists


A constructor for a derived class can use the initializer list mechanism to pass values along to a base-
class constructor. Consider this example:


derived::derived(type1 x, type2 y) : base(x,y) // initializer list
{
...
}


Here, derived is the derived class, base is the base class, and x and y are variables used by the base-
class constructor. If, say, the derived-class constructor receives the arguments 10 and 12, this mecha-
nism then passes 10 and 12 on to the base-class constructor defined as taking arguments of these
types. Except for the case of virtual base classes (see Chapter 14, “Reusing Code in C++”), a class
can pass values back only to its immediate base class. However, that class can use the same mecha-
nism to pass back information to its immediate base class, and so on. If you don’t supply a base-class
constructor in a member initializer list, the program uses the default base-class constructor. The
member initializer list can be used only with constructors.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值