C++类虚函数表

来源:互联网 发布:限速路由器软件 编辑:程序博客网 时间:2024/05/03 13:57
#include <iostream>#include <cstdlib>using namespace std;class Base1{public:virtual void f(){cout << "Base1 f()" << endl;}virtual void g(){cout << "Base1 g()" << endl;}virtual void h(){cout << "Base1 h()" << endl;}};class Base2{public:virtual void f(){cout << "Base2 f()" << endl;}virtual void g(){cout << "Base2 g()" << endl;}virtual void h(){cout << "Base2 h()" << endl;}};class Base3{public:virtual void f(){cout << "Base3 f()" << endl;}virtual void g(){cout << "Base3 g()" << endl;}virtual void h(){cout << "Base3 h()" << endl;}};class Base4{public:void f(){cout << "Base4 f()" << endl;}void g(){cout << "Base4 g()" << endl;}void h(){cout << "Base4 h()" << endl;}};class Child : public Base1, public Base2, public Base3, public Base4{public:void h(){cout << "Child h()" << endl;}virtual void e(){cout << "Child e()" << endl;}/*virtual*/ long &getRef(){return value;}private:long value;};int _tmain(int argc, _TCHAR* argv[]){Child c;cout << sizeof(c) << endl;typedef void (*FUNC)();FUNC pFunc;int **ptrTable = (int **)&c;cout << &c << endl;cout << &ptrTable[0] << endl;cout << &ptrTable[1] << endl;cout << &ptrTable[2] << endl;long &value = c.getRef();cout << &value << endl;cout << "---------------------------------" << endl;pFunc = (FUNC)ptrTable[0][0];pFunc();pFunc = (FUNC)ptrTable[0][1];pFunc();pFunc = (FUNC)ptrTable[0][2];pFunc();pFunc = (FUNC)ptrTable[0][3];pFunc();// 注意getRef前的virtual修饰符//pFunc = (FUNC)ptrTable[0][4];//pFunc();cout << "---------------------------------" << endl;pFunc = (FUNC)ptrTable[1][0];pFunc();pFunc = (FUNC)ptrTable[1][1];pFunc();pFunc = (FUNC)ptrTable[1][2];pFunc();cout << "---------------------------------" << endl;pFunc = (FUNC)ptrTable[2][0];pFunc();pFunc = (FUNC)ptrTable[2][1];pFunc();pFunc = (FUNC)ptrTable[2][2];pFunc();cout << "---------------------------------" << endl;system("pause");return 0;}

0 0