重载、覆盖与隐藏

下面函数中Base::f(int x)与Base::f(float x)是互为重载,Base::g(void)被Derived::g(void)覆盖

#include <iostream>
#include <stdio.h>
using namespace std;

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

class Derived : public Base
{
public:
    virtual void g(void) { cout << "Derived::g(void)" << endl; }
};

int main(void)
{
    Derived d;
    Base *pb = &d;
    pb->f(42);
    printf("11111111111111\n");
    pb->f(3.14f);
    printf("22222222222222\n");
    pb->g();
    return 0;
}

下面的例子中:

(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(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; }
};

 

posted @ 2017-09-27 14:26  哈利波波特  阅读(8)  评论(0)    收藏  举报