通过指针引用虚函数

对于一个带有虚函数的类中,他的对象的内存结构可以参考我以前发表的相关文章

下面这个例子从多个角度来找到虚函数的指针,并对其进行调用

方法一:定义一个对象找到对象中存放的虚函数所在表的头指针,并将其第一个指针作为我们调用的函数指针

方法二:直接通过二级指针找到函数指针

 

#include<stdio.h>
#include <iostream> //cout hex ……
#include <iomanip>  //setw

using namespace std;
#define PRINT_SIZE(CLASS_NAME) /
cout << "The size of " << #CLASS_NAME << " is " << sizeof(CLASS_NAME) << endl;

#define PRINT_DETAIL(CLASS_NAME, OBJECT_NAME) /
cout << "The detail of " << #CLASS_NAME << " is "; /
for (int i = 0; i < sizeof(OBJECT_NAME); ++i) { /
cout.fill('0'); /
cout << setw(2) << hex << ((short)((char*)(&(OBJECT_NAME)))[i] & 0x00ff); /
cout << ' '; } /
cout << setw(0) << dec << endl;

#define PRINT_SIZE_DETAIL(CLASS_NAME) /
PRINT_SIZE(CLASS_NAME) /
CLASS_NAME _##CLASS_NAME; /
PRINT_DETAIL(CLASS_NAME, _##CLASS_NAME)

class A
{
public:
        virtual int Calc2(int a);
        //int Calc2(int a);
};

int A::Calc2(int a)
{
        return 1;
}


int main( )
{
        int ret = 0;
        A *Ao = new A() ;
        unsigned long *pul;
        unsigned long **ppul;
        A a;
        PRINT_SIZE_DETAIL(A);
        //ret = Ao->Calc2(0xFFFF);
       
       
        //pul = (unsigned long *)0x00444c80;
        pul = (unsigned long *)(&a);
        ppul = (unsigned long **)(&a);
        printf("ret=%08X/n",**ppul);
        for(ret =0;ret<4;ret++)
        {
         cout.fill('0');
   cout << setw(2) << hex << ((short)((char*)(pul))[ret] & 0x00ff);
   cout << ' ';
        }
        int (*p)(int);
        //p = (int (*)(int))0x00401150;
        p = (int (*)(int))**ppul;
        ret = (*p)(1);
        printf("ret=%d/n",ret);
       
        ret = Ao->Calc2(0xFFFF);
        printf("ret=%d/n",ret);
        return 0;
}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值