#includeusing 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: //为了便于测试,特别该用public int x = 100; int y = 200; }; class Son : public Father { public: void func1() { cout << "Son::func1" << endl; } virtual void func5() { cout << "Son::func5" << endl; } }; typedef void (*func_t)(void); int main(void) { Father father; Son son; // 含有虚函数的对象的内存中,最先存储的就是“虚函数表” cout << "son对象地址:" << (int*)&son << endl; int* vptr = (int*)*(int*)&son; cout << "虚函数表指针vptr:" << vptr << endl; for (int i = 0; i < 4; i++) { cout << "调用第" << i + 1 << "个虚函数:"; ((func_t) * (vptr + i))(); } for (int i = 0; i < 2; i++) { // +4 是因为先存储了虚表指针 cout << *(int*)((int)&son + 4 + i * 4) << endl; } system("pause"); return 0; }
执行效果:



