zoukankan      html  css  js  c++  java
  • 如何通过指针访问虚函数表,并且调用里面的方法

    昨天面头条,,,最后面试官问道如何用指针访问虚函数表的东西。。。然后瞎写了一通,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;
    }
  • 相关阅读:
    POJ 3468 线段树 成段更新 懒惰标记
    hdu 1717
    3个技巧让你正能量满满
    this指针基础介绍
    数组指针和指针数组的区别
    for循环的执行顺序
    读取文本文件里的数字求平均值
    break与continue的区别
    谈谈 静坐
    医生告诉我们的常识.读完它吧,你会一生受益
  • 原文地址:https://www.cnblogs.com/ccXgc/p/8932759.html
Copyright © 2011-2022 走看看