1. 程式人生 > >類成員函式的過載、覆蓋和隱藏區別?

類成員函式的過載、覆蓋和隱藏區別?

#include <iostream>
#include <complex>
using namespace std;

class Base
{
public:
    virtual void a(int x)    {    cout << "Base::a(int)" << endl;      }
    // overload the Base::a(int) function
    virtual void a(double x) {    cout << "Base::a(double)" << endl;   }
    virtual void b(int x)    {    cout << "Base::b(int)" << endl;      }
    void c(int x)            {    cout << "Base::c(int)" << endl;      }
};


class Derived : public Base
{
public:
    // redefine the Base::a() function
    void a(complex<double> x)   {    cout << "Derived::a(complex)" << endl;      }
    // override the Base::b(int) function
    void b(int x)               {    cout << "Derived::b(int)" << endl;          }
    // redefine the Base::c() function
    void c(int x)               {    cout << "Derived::c(int)" << endl;          }
};


int main()
{
    Base b;
    Derived d;
    Base* pb = new Derived;
    // ----------------------------------- //
    b.a(1.0);                              // Base::a(double)
    d.a(1.0);                              // Derived::a(complex)
    pb->a(1.0);                            // Base::a(double), This is redefine the Base::a() function
    // pb->a(complex<double>(1.0, 2.0));   // clear the annotation and have a try
    // ----------------------------------- //
    b.b(10);                               // Base::b(int)
    d.b(10);                               // Derived::b(int)
    pb->b(10);                             // Derived::b(int), This is the virtual function
    // ----------------------------------- //
    delete pb;


    return 0;
}

1.Base類中的第二個函式a是對第一個的過載。
2.Derived類中的函式b是對Base類中函式b的重寫,即使用了虛擬函式特性。
3.Derived類中的函式a是對Base淚中函式a的隱藏,即重定義了。
4.因為Base類的函式c沒有定義為virtual虛擬函式,所以Derived類的函式c是對Base::c()的重定義。
5.pb指標是一個指向Base型別的指標,但是它實際指向了一個Derived的空間,這裡對pd呼叫函式的處理(多型性)
  取決於是否重寫(虛擬函式特性)了函式,若沒有,則依然呼叫基類。
6.只有在通過基類指標或基類引用 間接指向派生類型別時多型性才會起作用