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

VC++深入详解:函数的覆盖和隐藏

时间:2009-12-30 15:42来源:未知 作者:admin 点击:
分享到:
1.函数的覆盖 在上一节介绍多态性的时候,我们给出了下面的代码片段: 例2-19 class animal { public: … virtual void breathe() { cout"animal breathe"endl; } }; class fish:public animal { public: void breathe()

  1.函数的覆盖

  在上一节介绍多态性的时候,我们给出了下面的代码片段:

  例2-19

   class animal
  {
  public:
     …
   virtual void breathe()
   {
     cout<<"animal breathe"<<endl;
   }
  };
  class fish:public animal
  {
  public:
   void breathe()
   {
     cout<<"fish bubble"<<endl;
   }
  };

  在基类animal的breathe函数前添加了virtual关键字,声明该函数为虚函数。在派生类fish中重写了breathe函数,我们注意到,fish类的breathe函数和animal类的breathe函数完全一样,无论函数名,还是参数列表都是一样的,这称为函数的覆盖(override)。构成函数覆盖的条件为:

  n 基类函数必须是虚函数(使用virtual关键字进行声明)。

  n 发生覆盖的两个函数要分别位于派生类和基类中。

  n 函数名称与参数列表必须完全相同。

  由于C++的多态性是通过虚函数来实现的,所以函数的覆盖总是和多态关联在一起。在函数覆盖的情况下,编译器会在运行时根据对象的实际类型来确定要调用的函数。

  2.函数的隐藏

  我们再看例2-20的代码:

  例2-20

  class animal
  {
  public:
     …
   void breathe()
   {
     cout<<"animal breathe"<<endl;
   }
  };
  class fish:public animal
  {
  public:
void breathe()
   {
     cout<<"fish bubble"<<endl;
   }
  };

精彩图集

赞助商链接