c++中的隐藏、重载、覆盖(多态)



 1 重载、覆盖、隐藏

    成员函数被重载的特征:

(1)相同的范围(在同一个类中);

(2)函数名字相同;

(3)参数不同;

(4)virtual关键字可有可无。

    覆盖是指派生类函数覆盖基类函数(多态),特征是:

(1)不同的范围(分别位于派生类与基类);

(2)函数名字相同;

(3)参数相同;

(4)基类函数必须有virtual关键字。

   隐藏是指派生类的函数屏蔽了与其同名的基类函数,特征是:
  
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏(注意别与重载混淆)。

(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数被隐藏(注意别与覆盖混淆)。

例子1:

#include <iostream.h>
class Base
{
public:
    virtual void f(float x){ cout << "Base::f(float) " << x << endl; }
  void g(float x){ cout << "Base::g(float) " << x << endl; }
  void h(float x){ cout << "Base::h(float) " << x << endl; }
}; 

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

void main(void)
{
    Derived d;
    Base *pb = &d;
   Derived *pd = &d;
// Good : behavior 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 : behavior 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 : behavior 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
} 

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

 
例子2:

class Base
{
public:
 virtual Base& operator=(const Base& rhs)  //重载操作符可设为virtual 
 {
  cout << "Base" << endl;
  return *this;
 }

};

class Derived : public Base
{
public:
 //与基类的operator=完全不同,不是重新定义,不会动态绑定。 
 //如果不定义该操作符,会自动合成一个,并自动调用基类的operator=,不会动态绑定 
 virtual Derived& operator=(const Derived& rhs)
 {
  cout << "Derived_D" << endl;
  return *this;
 }

 //重新定义基类的operator=,会动态绑定 
 //virtual Base& operator=(const Base& rhs)  //返回值两种都可以 
 virtual Derived& operator=(const Base& rhs)
 {
    cout << "Derived_B" << endl;
    return *this;
 }
};

//class Derived2 : public Derived
//{
// //此类需要3个operator= 
// //可定义private的copy函数,由3个operator=调用 
// //可使用dynamic_cast将基类引用参数转为子类,并捕获异常。 
// //如果未发生异常,则调用copy,发生异常则不需赋值 
//};

int main()
{
 Base b1, b2;
 Derived d1, d2;
 
 Derived &rd = d1;

 Base &rb1 = b1;  //动态类型为Base 
 Base &rb2 = d2;  //动态类型为Derived 

 rb1 = d1;  //输出"Base"         //基类对象调用基类方法
 rb2 = d2;  //输出"Derived_B"    //用基类的引用调用派生类的方法,必须要基类中要定义该方法(用virtual关键字修饰,实现多态),然后到派生类中覆盖掉该方法

 rb1 = rb2;  //输出"Base" 
 rb2 = rb1;  //输出"Derived_B" 

 rd = d1;  //输出"Derived_D"     
 rd = b1;  //输出"Derived_B"   //派生类对象调用派生类方法,会选择一个最适合的方法调用。

 getchar();
 return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值