单继承时虚函数表解析

1.派生类先继承基类的虚函数表,如果派生类重新定义基类的虚函数,则会覆盖相应的表项,如果派生类定义了新的虚函数,则按照声明的顺序扩充虚函数表。
2. 注意:对于同时存在于基类和派生类的虚函数,派生类虚函数表的顺序是按照基类虚函数的声明顺序排列的,与派生类声明顺序无关(微信面试题)。

#include <iostream>
#include <cmath>

using namespace std;


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

};

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

int main()
{
    Base base;
    typedef void(*pFun)();
    pFun pfun;
    cout << "Based---------------------------------------" << endl;
    for (int i = 0; i < 3; i++)
    {
        pfun = (pFun)*((int *)*(int *)(&base) + i);
        pfun();
    }
    cout << "Derived-------------------------------------" << endl;
    Derived derived;
    for (int i = 0; i < 4; i++)
    {
        pfun = (pFun)*((int *)*(int *)(&derived) + i);
        pfun();
    }

    return 0;
}

  

posted on 2016-10-02 11:43  lakeone  阅读(435)  评论(0编辑  收藏  举报

导航