有虚函数的类的对象都有一个指向虚表的虚指针,虚表指针位于对象的起始地址,虚表记录了虚函数的地址。
#include <iostream>
using namespace std;
class F {
public:
virtual void vf1() {
cout << "F:vf1";
}
virtual void vf2() {
cout << "F:vf2";
}
};
class S : public F {
public:
void vf1() override {
cout << "S::vf1" << endl;
}
void vf2() override {
cout << "S::vf2" << endl;
}
};
int main() {
S s = S();
typedef void(*P)();//函数
long long v_ptr = *(long long *) &s;//强转成longlong,再解引用获得虚表的首部地址,8bit
P *f1 = (P *) v_ptr;
(*f1)(); // vf1
(*(f1 + 1))(); // vf2
return 0;
}