C++虚函数的实现机制是通过一个vtable表,指向子类的虚函数地址。
另外,如果不是虚函数,则不能实现用父类引用调用子类方法。
#include <windows.h> #include <iostream> using namespace std; class CBase { public: void fun() { cout << "CBase::fun" << endl; } virtual void vfun1() { cout << "CBase::vfun1" << endl; } virtual void vfun2() { cout << "CBase::vfun2" << endl; } }; class CDerive:public CBase { public: void fun() { cout << "CDerive::fun" << endl; } virtual void vfun1() { cout << "CDerive::vfun1" << endl; } }; int main(int argc, TCHAR* argv[]) { cout << "hello world!" << endl; CDerive derive; CBase* pBase = (CBase*)(&derive); pBase->fun(); pBase->vfun1(); pBase->vfun2(); cout << hex << *((int *)(*((int *)&derive))) << endl; cout << hex << *((int *)(*((int *)&derive)) + 1) << endl; cin.get(); return 0; }