标签:
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