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(); 这样就是调用相应的虚函数
本文深入探讨了C++中虚函数表的原理,详细解释了如何通过函数指针获取并调用虚函数。主要内容包括虚函数表的概念、获取虚函数表指针的方法以及如何使用该指针来调用特定的虚函数。

20万+

被折叠的 条评论
为什么被折叠?



