基类与子类的成员函数的关系

/****基类与子类的成员函数的关系*****/

#include "stdafx.h"
#include <iostream.h>

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

class Drived:public Base
{
public:
    void f(int i)
    { cout << "Drived::f(int i)" << endl;}
    void f(char* pchar)
    { cout << "Drived::f(char *)" << endl;}
    virtual void g(int)
    { cout << "Drived::g(int)" << endl;}
    virtual void g()
    { cout << "Drived::g()" << endl;}
    virtual h()
    { cout << "Drived::h()" << endl;}
};

int main(int argc, char* argv[])
{
    Base theBase;
   
    Drived theDrived;
   
    Base* pBase = &theBase;
   
    //
基类指针 指向 基类对象
    pBase->f((int)1.0);
    pBase->f();
    pBase->g();
   
    //
基类指针 指向 派生类对象
    pBase = &theDrived;
    pBase->g();
    pBase->f(2);
    pBase->f();
   
    //
派生类对象直接调用
    //theDrived.f();          //
隐藏关系,无法看到基类中的函数
    theDrived.f((int)1.0);
    theDrived.f("a");
    theDrived.g();
    //theDrived.h(1);         //
隐藏关系,无法看到基类中的函数
   
    //
语法说明
    //
派生类指针 指向 基类对象
    Drived* pDrived = (Drived*)&theBase;
    //pDrived->f();
    pDrived->f(10);
    //
注意,调用虚拟第0
    pDrived->g();
    //
注意,调用虚拟第1
    //pDrived->h();   
   
    //
派生类指针 指向 派生类对象
    pDrived = &theDrived;
    //pDrived->f();
    pDrived->f(10);
    pDrived->g();
    pDrived->h();
   
    return 0;
}

/**************************************************************************
class Base
{
public:
    void f()            
    void f(int i)
    virtual void g()        //1
    void h(int)
};

//
基类虚表
BaseVatabl =
{
    Base::g()
}

class Drived:public Base
{
public:
    void f(int i)       
    void f(char* pchar) 
    virtual void g(int)
    virtual void g()        //2  
    virtual void h()         
};

//
子类虚表
DrivedVatabl =
{
    Drived::g()
    Drived::g(int)
    Drived::h()
}


隐藏关系:两个成员函数名称一样,
但是分别在基类和派生类中。

//Base::f(); //Derived::f(int)
//Base::f(int i); //Derived::f(int i)

隐藏关系表现形式:派生类对象无法直接调用基类中f方法
//theDrived.f();  Error

重载关系: 两个成员函数名称一样,但是参数不同
           
但是一定在同一个类中

覆盖关系: 两个成员函数名称一样,参数,返回值类型一样,并且都是虚函数
           
但是分别在基类和派生类中。

隐藏关系:
    
注意: 两个成员函数名称一样,参数,返回值类型一样,基类没有Vitual修饰函数,
           
子类有Vitual,修饰函数,分别在基类和派生类中。

**************************************************************************/

原文地址:https://www.cnblogs.com/w413133157/p/1659537.html