关于虚函数

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.funcA(); funcB(); 这样就是调用相应的虚函数


 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值