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

VC++深入详解:类的继承[图](2)

时间:2009-12-30 15:42来源:未知 作者:admin 点击:
分享到:
重写animal和fish类,让fish从animal继承,代码如例2-11所示(EX05.CPP)。 例2-11 #include iostream.h class animal { public: void eat() { cout"animal eat"endl; } void sleep() { cout"an

  重写animal和fish类,让fish从animal继承,代码如例2-11所示(EX05.CPP)。

  例2-11

  #include <iostream.h>
  class animal
  {
  public:
     void eat()
     {
       cout<<"animal eat"<<endl;
     }
void sleep()
     {
       cout<<"animal sleep"<<endl;
     }
     void breathe()
     {
       cout<<"animal breathe"<<endl;
     }
  };
  class fish:public animal
  { 
  };
  void main()
  {
     animal an;
     fish fh;
     an.eat();
     fh.eat();
  }

  虽然fish类没有显式地编写一个方法,但fish从animal已经继承eat、sleep、breathe方法,我们通过编译运行可以看到结果。

  下面,我们在animal类和fish类中分别添加构造函数和析构函数,然后在main函数中定义一个fish类的对象fh,看看在构造fish类的对象时,animal类的构造函数是否被调用;如果调用,animal类和fish类的构造函数的调用顺序是怎样的。完整代码如例2-12所示(EX06.CPP)。

  例2-12

  #include <iostream.h>
  class animal
  {
  public:
     animal()
     {
       cout<<"animal construct"<<endl;
     }
     ~animal()
     {
       cout<<"animal destruct"<<endl;

精彩图集

赞助商链接