《子类调用父类带参数的构造函数.doc》由会员分享,可在线阅读,更多相关《子类调用父类带参数的构造函数.doc(3页珍藏版)》请在金锄头文库上搜索。
1、在子类中调用父类的带参数的构造函数下面我们修改一下animal类的构造函数,增加两个参数height和weight,在子类中调用父类的带参数的构造函数,分别表示动物的高度和重量,代码如例2-13所示,类中普通的成员变量也可以采取此种方式进行初始化,然而,例2-13#include class animalpubli下面我们修改一下animal类的构造函数,增加两个参数height和weight,分别表示动物的高度和重量。代码如下所示。#include class animalpublic: animal(int height, int weight) coutanimal constructe
2、ndl; animal() coutanimal destructendl; void eat() coutanimal eatendl; void sleep() coutanimal sleependl; void breathe() coutanimal breatheendl; ;class fish:public animalpublic: fish() coutfish constructendl; fish() coutfish destructendl; ;void main() fish fh;当我们编译这个程序时,就会出现如下错误:那么这个错误是如何出现的呢?当我们构造fi
3、sh类的对象fh时,它需要先构造animal类的对象,调用animal类的默认构造函数(即不带参数的构造函数),而在我们的程序中,animal类只有一个带参数的构造函数,在编译时,因找不到animal类的默认构造函数而出错。因此,在构造fish类的对象时(调用fish类的构造函数时),要想办法去调用animal类的带参数的构造函数,那么,我们如何在子类中向父类的构造函数传递参数呢?可以采用如例2-14所示的方式,在构造子类时,显式地去调用父类的带参数的构造函数。例2-14#include class animalpublic:animal(int height, int weight)cout
4、animal constructendl;class fish:public animalpublic:fish():animal(400,300)coutfish constructendl;void main()fish fh;注意程序中以粗体显示的代码。在fish类的构造函数后,加一个冒号(:),然后加上父类的带参数的构造函数。这样,在子类的构造函数被调用时,系统就会去调用父类的带参数的构造函数去构造对象。这种初始化方式,还常用来对类中的常量(const)成员进行初始化,如下面的代码所示:class pointpublic: point():x(0),y(0)private: const int x; const int y;当然,类中普通的成员变量也可以采取此种方式进行初始化,然而,这就没有必要了。