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;
    }
  • 相关阅读:
    SELECT SCREEN 整理2 转载
    SELECT SCREEN 整理1 转载
    ABAP面向对象 转载
    [OO]ABAP OO 语法--实例看 "="与"?=" 的区别[转]
    cl_salv_table
    sapui5 组件重用
    sapui5 使用common(其他工程)的i18n 文件
    sapui5 app之间迁移
    导航与路由10-17(渣翻完结)
    导航与路由1-9 (渣翻)
  • 原文地址:https://www.cnblogs.com/ccXgc/p/8932759.html
Copyright © 2011-2022 走看看