在子类中调用父类的带参数的构造函数

27 篇文章 0 订阅

animal类的构造函数,增加两个参数height和weight,分别表示动物的高度和重量。代码如例2-13所示。

  例2-13

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include < iostream.h >
class animal
{
public:
   animal(int height, int weight)
   {
     cout<<"animal construct"<<endl;
   }
   ~animal()
   {
     cout<<"animal destruct"<<endl;
   }
   void eat()
   {
     cout<<"animal eat"<<endl;
   }
   void sleep()
   {
     cout<<"animal sleep"<<endl;
   }
   void breathe()
   {
     cout<<"animal breathe"<<endl;
   }
};
class fish:public animal
{
public:
   fish()
   {
     cout<<"fish construct"<<endl;
   }
   ~fish()
   {
     cout<<"fish destruct"<<endl;
   }
};
void main()
{
   fish fh;
}

  当我们编译这个程序时,就会出现如下错误:

  

  那么这个错误是如何出现的呢?当我们构造fish类的对象fh时,它需要先构造animal类的对象,调用animal类的默认构造函数(即不带参数的构造函数),而在我们的程序中,animal类只有一个带参数的构造函数,在编译时,因找不到animal类的默认构造函数而出错。

  因此,在构造fish类的对象时(调用fish类的构造函数时),要想办法去调用animal类的带参数的构造函数,那么,我们如何在子类中向父类的构造函数传递参数呢?可以采用如例2-14所示的方式,在构造子类时,显式地去调用父类的带参数的构造函数。

  例2-14

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include < iostream.h >
class animal
{
public:
  animal(int height, int weight)
  {
    cout<<"animal construct"<<endl;
  }
  …
};
class fish:public animal
{
public:
  fish():animal(400,300)
  {
    cout<<"fish construct"<<endl;
  }
  …
};
void main()
{
  fish fh;
}

  注意程序中以粗体显示的代码。在fish类的构造函数后,加一个冒号(:),然后加上父类的带参数的构造函数。这样,在子类的构造函数被调用时,系统就会去调用父类的带参数的构造函数去构造对象。这种初始化方式,还常用来对类中的常量(const)成员进行初始化,如下面的代码所示:

双击代码全选
1
2
3
4
5
6
7
8
class point
{
public:
   point():x(0),y(0)
private:
   const int x;
   const int y;
};

  当然,类中普通的成员变量也可以采取此种方式进行初始化,然而,这就没有必要了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值