#include <iostream>
using namespace std;
class Father {
public:
virtual void func1() { cout << "Father::func1" << endl; }
virtual void func2() { cout << "Father::func2" << endl; }
virtual void func3() { cout << "Father::func3" << endl; }
void func4() { cout << "非虚函数:Father::func4" << endl; }
public:
int x = 200;
int y = 300;
static int z;
};
class Mother {
public:
virtual void handle1() { cout << "Mother::handle1" << endl; }
virtual void handle2() { cout << "Mother::handle2" << endl; }
virtual void handle3() { cout << "Mother::handle3" << endl; }
public: //为了便于测试,使用public权限
int m = 400;
int n = 500;
};
class Son : public Father, public Mother {
public:
void func1() { cout << "Son::func1" << endl; }
virtual void handle1() { cout << "Son::handle1" << endl; }
virtual void func5() { cout << "Son::func5" << endl; }
};
int Father::z = 0;
typedef void(*func_t)(void);
int main(void) {
Son son;
int* vptr = (int*) * (int*)&son;
cout << "第一个虚函数表指针:" << vptr << endl;
for (int i = 0; i < 4; i++) {
cout << "调用第" << i + 1 << "个虚函数:";
((func_t) * (vptr + i))();
}
for (int i = 0; i < 2; i++) {
cout << *(int*)((int)&son + 4 + i * 4) << endl;
}
int* vptr2 = (int*) * ((int*)&son + 3);
for (int i = 0; i < 3; i++) {
cout << "调用第" << i + 1 << "个虚函数:";
((func_t) * (vptr2 + i))();
}
for (int i = 0; i < 2; i++) {
cout << *(int*)((int)&son + 16 + i * 4) << endl;
}
system("pause");
return 0;
}
执行结果
VS分析:
内存分布