[C++基础]025_虚函数和虚函数表

首先有一个有趣的东西:如何不通过对象来访问对象中的虚函数呢?我们来看下面这样一段代码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 typedef void (*Fun)(void); // 函数指针
 5 
 6 class A{
 7 public:
 8     virtual void testA(void){
 9         cout<<"A is Print."<<endl;
10     }
11 
12     virtual void testB(void){
13         cout<<"B is Print."<<endl;
14     }
15 };
16 
17 int main(){
18     A a;
19     Fun function = NULL;
20     cout<<"对象a的地址:"<<&a<<endl;
21     cout<<"虚函数表地址:"<<(int*)(&a)<<endl;
22     cout<<"虚函数表中第一个虚函数地址"<<(int*)*(int*)(&a)<<endl;
23     function = (Fun)*((int*)*(int*)(&a));
24     function();
25     system("pause");
26     return 0;
27 }

输出结果:

对象a的地址:0043FF1C
虚函数表地址:0043FF1C
虚函数表中第一个虚函数地址01367880
A is Print.
请按任意键继续. . .

可见,通过【(int*)*(int*)(&a)】就可以获取对象a的第一个虚函数地址,通过【(int*)*(int*)(&a)+1】就可以获取第二个虚函数的地址,从而就可以调用该对象的虚函数了。

通过函数指针可以访问虚函数的核心是因为有一个【虚函数表】的东西存在着,本文就不赘述了,有一篇博客写的相当清晰,见链接:http://blog.csdn.net/haoel/article/details/1948051/

posted @ 2012-10-13 00:23  邵贤军  阅读(375)  评论(0编辑  收藏  举报