码迷,mamicode.com
首页 > 其他好文 > 详细

获取类中虚函数地址

时间:2015-07-12 15:31:18      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

// 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; }

 

获取类中虚函数地址

标签:

原文地址:http://www.cnblogs.com/xiumukediao/p/4640919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!