// CMemory.cpp : Defines the entry point for the console application. // #include "stdafx.h" #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; } }; class Derive:public Base{ public: virtual void f() { cout << "Derive::f" << endl; } // virtual void g() { cout << "Derive::g" << endl; } virtual void h() { cout << "Derive::h" << endl; } }; int main(int argc, char* argv[]) { typedef void (*Pfunc)(void); Base b; cout<<"vptr addr: "<<(int *)&b<<endl; cout<<"first func addr: "<<(int *)(*(int *)&b+0)<<endl; cout<<"second func addr: "<<(int *)(*(int *)&b)+1<<endl; cout<<"third func addr: "<<(int *)(*(int *)&b)+2<<endl; Pfunc funcf = (Pfunc)*((int *)(*(int *)&b)+0); Pfunc funcg = (Pfunc)*((int *)(*(int *)&b)+1); Pfunc funch = (Pfunc)*((int *)(*(int *)&b)+2); funcf(); funcg(); funch(); Derive d ; cout<<"vptr addr: "<<(int *)&d<<endl; cout<<"first func addr: "<<(int *)(*(int *)&d+0)<<endl; cout<<"second func addr: "<<(int *)(*(int *)&d)+1<<endl; cout<<"third func addr: "<<(int *)(*(int *)&d)+2<<endl; Pfunc dfuncf = (Pfunc)*((int *)(*(int *)&d)+0); Pfunc dfuncg = (Pfunc)*((int *)(*(int *)&d)+1); Pfunc dfunch = (Pfunc)*((int *)(*(int *)&d)+2); dfuncf(); dfuncg(); dfunch(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //多继承时继承类拥有n个虚函数表,继承了n各类 int ** pVtab = (int**)&d; //二维数组,第一维:第几个虚函数表,第二维:虚函数表中第几个虚函数 Pfunc dd = (Pfunc)pVtab[0][0]; dd(); return 0; }
时间: 2024-11-07 03:19:48