#include <bits/stdc++.h>
using namespace std;

class Base {
public:
Base() {
cout << "Base构造" << endl;
}
virtual ~Base() {
cout << "Base虚析构" << endl;
}
virtual void f1() {
cout << "Base::f1()" << endl;
}
void f2() {
cout << "Base::f2()" << endl;
}
virtual void f3() {
cout << "Base::f3()" << endl;
//cout << data << endl;
}
int data = 5;
static void fn() {
}
};

int main() {
cout << sizeof(Base) << endl;

Base* p1 = new Base();
Base* p2 = new Base();
cout << p1->fn << endl; // 静态成员函数可以直接获取地址
cout << Base::fn << endl; // 静态成员函数可以直接获取地址

// cout << &Base::f1 << endl; // 编译器将void(__thiscall A::*)()类型转换为bool类型
printf("Base::f1()地址:%p\n", &Base::f1);
printf("Base::f1()地址:%p\n", &Base::f1);
printf("Base::f2()地址:%p\n", &Base::f2);
printf("Base::fn()地址:%p\n", &Base::fn);

cout << "p1对象地址: " << (p1) << endl;
cout << "p1虚函数表首地址: " << (int*)(p1) << endl;
cout << "p1虚函数表中第1个虚函数地址: " << (int*)*(int*)(p1) << endl;
cout << "p1虚函数表中第2个虚函数地址: " << ((int*)*(int*)(p1)+1) << endl;
cout << "p1虚函数表中第3个虚函数地址: " << ((int*)*(int*)(p1)+2) << endl;
cout << "p1虚函数表中第4个虚函数地址: " << ((int*)*(int*)(p1)+3) << endl;


cout << "p2对象地址: " << (p2) << endl;
cout << "p2虚函数表首地址: " << (int*)(p2) << endl;
cout << "p2虚函数表中第1个虚函数地址: " << (int*)*(int*)(p2) << endl;
cout << "p2虚函数表中第2个虚函数地址: " << ((int*)*(int*)(p2)+1) << endl;
cout << "p2虚函数表中第3个虚函数地址: " << ((int*)*(int*)(p2)+2) << endl;
cout << "p2虚函数表中第4个虚函数地址: " << ((int*)*(int*)(p2)+3) << endl;

cout << endl;

typedef void(*PFUN)();

PFUN pfBase = (PFUN) * ((int*)*(int*)p1 + 0); // 析构
PFUN pf1 = (PFUN) * ((int*)*(int*)p1 + 1); // f1
PFUN pf2 = (PFUN) * ((int*)*(int*)p1 + 2); // f2
PFUN pfnull = (PFUN) * ((int*)*(int*)p1 + 3); //0x00
pf1();
pf2(); // 如果函数中有类成员变量,这样调用会出错。普通变量不会。和this指针有关。

}

​C/C++获取函数地址​