再谈虚函数

虚函数
http://blog.csdn.net/hustli/archive/2003/07/02/19357.aspx
http://blog.csdn.net/ox_thedarkness/archive/2006/02/27/611370.aspx
http://blog.csdn.net/pandaxiaoxi/archive/2006/07/02/864025.aspx
http://blog.csdn.net/Nicrosoft/archive/2001/04/25/4030.aspx
http://blog.csdn.net/wangwang1103/archive/2006/07/01/858726.aspx
http://blog.csdn.net/simonwan/archive/2005/04/19/354169.aspx
http://blog.csdn.net/zhc/archive/2001/10/28/2730.aspx

以下均为转载:
 奇巧淫技 ――― C++ 直接操纵虚函数表
     CSDN Blog推出文章指数概念,文章指数是对Blog文章综合评分后推算出的,综合评分项分别是该文章的点击量,回复次数,被网摘收录数量,文章长度和文章类型;满分100,每月更新一次。
以下代码没有什么实用价值,最多拿来加深一下对虚函数表的印象,一时性起,想直接操纵虚函数表。这段代码只尝试了在VS2005上编译通过,没有在其他编译器上尝试,它并不具有可移植性。
 
大家都知道C++的虚函数机制通常是通过一个虚函数表来实现的,C++不对内存访问做限制,所以我们可以通过指针自己访问虚函数表,然后进行操作。
 
#include <iostream>
 
using namespace std;
 
 
class B
{
public:
     virtual void fun1()
     {
         cout<<"B::fun1"<<endl;
     }
 
    virtual void fun2()
     {
         cout<<"B::fun2"<<endl;
     }
 
};
 
int main()
{
     typedef void(*FUN)();
 
     B b;
     void** ptable = *(void***)&b;
    
     FUN f1 = (FUN)(*ptable);
     f1();
 
     FUN f2 = *((FUN*)((FUN*)(ptable) + 1));
     f2();
 
}
 
输出
B::fun1
B::fun2
 

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1530081

原文地址:https://www.cnblogs.com/cutepig/p/925404.html