zoukankan      html  css  js  c++  java
  • 获取类中虚函数地址

    // CMemory.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <IOSTREAM>
    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 Derive:public Base{
    public:
        virtual void f() { cout << "Derive::f" << endl; }
    //    virtual void g() { cout << "Derive::g" << endl; }
        virtual void h() { cout << "Derive::h" << endl; }
    };
    
    int main(int argc, char* argv[])
    {
        typedef void (*Pfunc)(void);
        Base b;
        cout<<"vptr addr: "<<(int *)&b<<endl;
        cout<<"first func addr: "<<(int *)(*(int *)&b+0)<<endl;
        cout<<"second func addr: "<<(int *)(*(int *)&b)+1<<endl;
        cout<<"third func addr: "<<(int *)(*(int *)&b)+2<<endl;
        
        Pfunc funcf = (Pfunc)*((int *)(*(int *)&b)+0);
        Pfunc funcg = (Pfunc)*((int *)(*(int *)&b)+1);
        Pfunc funch = (Pfunc)*((int *)(*(int *)&b)+2);
        funcf();
        funcg();
        funch();
    
        Derive d ;
        cout<<"vptr addr: "<<(int *)&d<<endl;
        cout<<"first func addr: "<<(int *)(*(int *)&d+0)<<endl;
        cout<<"second func addr: "<<(int *)(*(int *)&d)+1<<endl;
        cout<<"third func addr: "<<(int *)(*(int *)&d)+2<<endl;
        
        Pfunc dfuncf = (Pfunc)*((int *)(*(int *)&d)+0);
        Pfunc dfuncg = (Pfunc)*((int *)(*(int *)&d)+1);
        Pfunc dfunch = (Pfunc)*((int *)(*(int *)&d)+2);
        dfuncf();
        dfuncg();
        dfunch();
    
      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      //多继承时继承类拥有n个虚函数表,继承了n各类
    int ** pVtab = (int**)&d; //二维数组,第一维:第几个虚函数表,第二维:虚函数表中第几个虚函数 Pfunc dd = (Pfunc)pVtab[0][0]; dd(); return 0; }
  • 相关阅读:
    工作感悟(一)
    laydate组件选择时间段的判断
    Win10下免安装版JDK8环境变量配置
    IDEA中lombok插件的安装
    解决加载WEB页面时,由于JS文件引用过多影响页面打开速度的问题
    Windows环境下的MYSQL5.7配置文件定位
    MYSQL使用source命令,导入SQL文件
    MYSQL5.7生成列简介及创建
    MYSQL慢查询优化方法及优化原则
    批量提取文件夹下所有目录及文件名称
  • 原文地址:https://www.cnblogs.com/xiumukediao/p/4640919.html
Copyright © 2011-2022 走看看