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

关于虚函数

时间:2015-08-25 23:44:03      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

typedef void (*fun)();
class A
{
public:
	A()
	{
		cout << "class A default constructor called" << endl;
		a = 0;
	}
	A(int param)
	{
		cout << "class A constructor called" << endl;
		a = param;
	}
	~A()
	{

	}
	virtual void FunctionA()
	{
		cout << "classA FunctionA()" << endl;
	}
	virtual void FunctionB()
	{
		cout << "classA FunctionB()" << endl;
	}
	int a;
	static int staticA;
private:

};
int  A::staticA = 2;
int main()
{
   A aObj;
   fun  funcA =  (fun) *((int*)*(int*)(&aObj));
   funcA();
   fun  funcB =  (fun) *( (int*)*(int*)(&aObj) + 1);
   funcB();
   while(1);
   return 0;
}

技术分享
1.(int*)(*aObj)得到了虚函数表指针的地址&vptr

2.(int*)*(int*)(*aObj)得到虚函数表指针vptr 指针的类型是(int*),这时需要转化下

3.vptr是指向vptr table,其实就是指向一个数组,数组元素是函数指针。 

    (int*)*(int*)(*aObj) 指向数组第一个元素  所以*((int*)*(int*)(*aObj))就是FunctionA的地址 

    (int*)*(int*)(*aObj) + 1 指向数组第二个元素,所以*((int*)*(int*)(*aObj) + 1) 就是FunctionB的地址

4.func() 这样就是调用相应的虚函数


 


版权声明:本文为博主原创文章,未经博主允许不得转载。

关于虚函数

标签:

原文地址:http://blog.csdn.net/king__moving/article/details/47987553

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