养浩然之气,活着不是为技术,请关心身边的人.

(转)重载、覆盖与隐藏

上一篇 / 下一篇  2007-09-26 11:23:36 / 个人分类:linux-C

重载与覆盖
成员函数被重载的特征:
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;
(4)virtual关键字可有可无。
覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有virtual关键字。

“隐藏”是指派生类的函数屏蔽了与其同名的基类函数,
规则如下:
(1)如果派生类的函数与基类的函数同名,但是参数不同。
     此时,不论有无virtual关键字,基类的函数将被隐藏(注意别与重载混淆)。
(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。
     此时,基类的函数被隐藏(注意别与覆盖混淆)。

如下示例程序中:
(1)函数Derived::f(float)覆盖了Base::f(float)。
(2)函数Derived::g(int)隐藏了Base::g(float),而不是重载。
(3)函数Derived::h(float)隐藏了Base::h(float),而不是覆盖。

#include<iostream.h>

class Base{
public:
virtual void f(floatx){cout<<"Base::f(float)"<<x<<endl;}
        void g(floatx){cout<<"Base::g(float)"<<x<<endl;
        void h(floatx){cout<<"Base::h(float)"<<x<<endl;}
};

class Derived:publicBase{
public:
virtual void f(floatx){cout<<"Derived::f(float)"<<x<<endl;}
        void g(intx){cout<<"Derived::g(int)"<<x<<endl;}
        void h(floatx){cout<<"Derived::h(float)"<<x<<endl;}
};
void main(void){
  Derived d;
  Base *pb=&d;
  Derived *pd=&d;
  
  //Good:behavīor depends solely on type of the object
  pb->f(3.14f);     //Derived::f(float)3.14
  pd->f(3.14f);     //Derived::f(float)3.14

  //Bad:behavīor depends on type of the pointer
  pb->g(3.14f);     //Base::g(float)3.14
  pd->g(3.14f);     //Derived::g(int)3(surprise!)

  //Bad:behavīor depends on type of the pointer
  pb->h(3.14f);     //Base::h(float)3.14(surprise!)
  pd->h(3.14f);     //Derived::h(float)3.14
}

trackback:http://blog.csdn.net/wcp872123/archive/2005/02/03/279119.aspx


TAG: linux-C

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

数据统计

  • 访问量: 21851
  • 日志数: 146
  • 建立时间: 2007-08-01
  • 更新时间: 2008-02-20

RSS订阅

Open Toolbar