#include <iostream>
using namespace std;
class Base {
public:
const char ch;
static int* p1;
static int* p2;
Base() : ch('A') {}
virtual void f1() { cout << "base:f1" << endl; }
virtual void f2() { cout << "base:f2" << endl; }
};
class Derive : public Base {
public:
const int num;
Derive() : num(100) {}
virtual void f1() { cout << "derive:f1" << endl; }
virtual void f2() { cout << "derive:f2" << endl; }
virtual void f3() { cout << "derive:f3" << endl; }
};
typedef void (*FUNC)(void);
Derive d = Derive();
// Base* d = new Derive();
FUNC pfunc1 = (FUNC) * (long *) * ( (long *) &d );
FUNC pfunc2 = (FUNC) * ((long *) * ( (long *) &d ) + 1);
FUNC pfunc3 = (FUNC) * ((long *) * ( (long *) &d ) + 2);
int main() {
cout << &d << endl; // 取对象d在内存中的地址
cout << (long *) &d << endl; // (long *)对对象入口地址强转
cout << * (long *) &d << endl; // 解引用,获得对象虚函数指针的值
// 对虚函数指针解引用(虚函数指针是二级指针)
// 获得虚函数表中第一个虚函数入口地址
cout << * (long *) * ( (long *) &d) << endl;
pfunc1();
pfunc2();
pfunc3();
return 0;
}
output
0x602250
0x602250
4197560
4197228
derive:f1
derive:f2
derive:f3