测试C++虚表
#include <iostream>
using namespace std;
class base {
public:
virtual void f() { cout << "base::f" << endl; }
virtual void g() { cout << "base::g" << endl; }
virtual void h() { cout << "base::h" << endl; }
long a = 1;
};
class Derive : public base {
public:
void f() override {cout << "deriver::f" << endl; }
virtual void i() { cout << "derive::i" << endl; }
virtual void j() { cout << "derive::j" << endl; }
};
typedef void(*Fun)(void);
int main()
{
base b;
Derive d;
Fun pFun = nullptr;
cout << "the address of vtable:" << (long *)(&b) << endl;
cout << "the address of first func:" << (long*)*(long*)(&b) << endl;
cout << "the member of base " << *((long *)(&b) + 1) << endl;
pFun = (Fun)*((long*)*(long*)(&b));
pFun();
pFun = (Fun)*((long*)*(long*)(&b) + 1);
pFun();
pFun = (Fun)*((long*)*(long*)(&b) + 2);
pFun();
d.a = 1;
cout << "the address of vtable:" << (long *)(&d) << endl;
cout << "the address of first func:" << (long*)*(long*)(&d) << endl;
cout << "the member of derive " << *((long*)*(long*)(&d) + 5) << endl;
pFun = (Fun)*((long*)*(long*)(&d));
pFun();
pFun = (Fun)*((long*)*(long*)(&d) + 1);
pFun();
pFun = (Fun)*((long*)*(long*)(&d) + 2);
pFun();
pFun = (Fun)*((long*)*(long*)(&d) + 3);
pFun();
pFun = (Fun)*((long*)*(long*)(&d) + 4);
pFun();
return 0;
}
运行结果
the address of vtable:0x7fff0ae91750
the address of first func:0x558919f83d30
the member of base 1
base::f
base::g
base::h
the address of vtable:0x7fff0ae91760
the address of first func:0x558919f83cf8
the member of derive 0
deriver::f
base::g
base::h
derive::i
derive::j
|