如何通过指针访问虚函数表,并且调用里面的方法

昨天面头条,,,最后面试官问道如何用指针访问虚函数表的东西。。。然后瞎写了一通,gg了应该。

昨天的答案

fun = (Fun)((int)(((Base*)0)->f)+4);
fun()

 额。。。。昨天的代码是编译也通不过的。。。因为C++是无法获取 任何方法地址的。。。简单的demo测试。。。

#include <iostream>
using namespace std;

class A
{
public:
    A(){;}
    void f(){;}
    virtual void g(){;}
    static void h(){;}
};

int main()
{
    cout << &A::f << endl;
    cout << &A::g << endl;
    cout << &A::h << endl;
    cout << &A::f << endl;
    cout << &A::g << endl;
    cout << &A::h << endl;
    return 0;
}

 输出结果为

$ ./main
1
1
1
1
1
1

今天记录下如何用指针访问虚函数表,并且调用里面的方法。

#include <iostream>
using namespace std;

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

    virtual void h()
    {
        cout <<"Base:h" <<endl;
    }
};

class Derive: public Base
{
public:
    Derive(){;}
    void f()
    {
        cout <<"hello world" <<endl;
    }
    void g()
    {
        cout<<"Derive:g"<<endl;
    }
};

// 一个很有趣的问题。。。。为什么这里不需要用注释这中typedef...
//
//typedef void (*Fun)(Derive *ptr);
typedef void (*Fun)();

int main()
{
    Base *p = new Derive();
    long address = *(long*)p;
    cout<< address<< endl;
    Fun fun= (Fun)(*(long*)address);
    fun();
    fun = (Fun)(*(((long*)address)+1));
    fun();
    fun = (Fun)(*(((long*)address)+2));
    fun();
    fun = (Fun)(*(((long*)address)+3));
    return 0;
}
原文地址:https://www.cnblogs.com/ccXgc/p/8932759.html