#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
class A //定义一个类A,类中有3个虚函数
{
public:
int x;
int y;
virtual void f(){ cout << "f() called !" << endl; };
virtual void f1(){ cout << "f1() called !" << endl; };
virtual void f2(){ cout << "f2() called !" << endl; };
};
int main()
{
A a;
cout << hex ;
cout << "类的首地址:" << &a << endl;
//对于类的每个对象,编译器都会为其生成一个虚函数表指针,位于该对象内存中的开头,并指向了虚函数表的位置。
//&a得到对象a的首地址,强制转换为(int *),意为将从&a开始的4个字节看作一个整体,而&a就是这个4字节整体的首地址,也就是虚表指针。
cout << "虚函数表指针: " << (int *)(&a) << endl;
//虚函数表指针只想虚函数表,所以解引用就是虚函数表的地址
cout << "虚函数表地址: " << *(int *)(&a) << endl;
/*
下面获取虚函数地址(通过增加偏移量)
两种做法:(首先获取虚函数表地址addr)
1. 在虚函数表地址上 加字节偏移4*x(x从0开始),然后转换成指针,然后获取:
*(int *)(addr + 4*x);
2. 虚函数表地址 转换成指针,然后通过增加指针的偏移量x(x从0开始) 获取:
*((int *)addr + x);
*/
int addr = *(int *)(&a); //虚函数表地址
//f()地址
int f_addr_1 = *(int *)(addr + 0); //第1种
int f_addr_2 = *((int *)addr + 0); //第2种
cout<<"f()的地址:"<<f_addr_1<<' '<<f_addr_2<<'\n';
//f1()地址
int f1_addr_1 = *(int *)(addr + 4); //第1种
int f1_addr_2 = *((int *)addr + 1); //第2种
cout<<"f1()的地址:"<<f1_addr_1<<' '<<f1_addr_2<<'\n';
//f2()地址
int f2_addr_1 = *(int *)(addr + 8); //第1种
int f2_addr_2 = *((int *)addr + 2); //第2种
cout<<"f2()的地址:"<<f2_addr_1<<' '<<f2_addr_2<<'\n';
return 0;
}
感谢,参考与:这篇文章