设为首页 加入收藏

TOP

2.2.6 类的继承(2)
2013-10-07 15:20:23 来源: 作者: 【 】 浏览:71
Tags:2.2.6 继承

2.2.6  类的继承(2)

编译运行,出现如图2.11所示的结果。

可以看到当构造fish类的对象fh时,animal类的构造函数也要被调用,而且在fish类的构造函数调用之前被调用。当然,这也很好理解,没有父亲就没有孩子,因为fish类从animal类继承而来,所以在fish类的对象构造之前,animal类的对象要先构造。在析构时,正好相反。

 
图2.11  EX06.CPP程序的运行结果

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

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

例2-13

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

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

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

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

例2-14

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.2.6 类的继承(3) 下一篇2.2.6 类的继承(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: