龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > VC开发 >

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

时间:2009-12-30 15:42来源:未知 作者:admin 点击:
分享到:
下面我们修改一下animal类的构造函数,增加两个参数height和weight,分别表示动物的高度和重量。代码如例2-13所示。 例2-13 #include iostream.h class animal { public: animal(int height, int weight) { cout

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

  例2-13

  #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所示的方式,在构造子类时,显式地去调用父类的带参数的构造函数。

精彩图集

赞助商链接