假设如下单一继承关系:
C++代码如下:
class Parent {
public:
int iparent;
Parent():iparent(10) {}
virtual void f() { cout << "Parent::f()" << endl; }
virtual void g() { cout << "Parent::g()" << endl; }
virtual void h() { cout << "Parent::h()" << endl; }
};
class Child: public Parent {
public:
int ichild;
Child(): ichild(100) {}
virtual void f() { cout << "Child::f()" << endl; }
virtual void g_child() { cout << "Child::g_child()" << endl; }
virtual void h_child() { cout << "Child::h_child()" << endl; }
};
class GrandChild: public Child {
public:
int igrandchild;
GrandChild(): igrandchild(1000) {}
virtual void f() { cout << "GrandChild::f()" << endl; }
virtual void g_child() { cout << "GrandChild::g_child()" << endl; }
virtual void h_grandchild() { cout << "GrandChild::h_grandchild()" << endl;}
};
测试代码如下:
int _tmain(int argc, _TCHAR* argv[])
{
typedef void(*Fun)(void); //函数类型
GrandChild gc;
int** pVtab = (int**)&gc;
cout << "[0] GrandChild::_ptr->" << endl;
for (int i=0; (Fun)pVtab[0][i] !=NULL; i++) {
Fun pFun = (Fun)pVtab[0][i];
cout << " ["<<i<<"] ";
pFun();
}
cout << "[1] Parent.iparent = " << (int)pVtab[1] << endl;
cout << "[2] Child.ichild = " << (int)pVtab[2] << endl;
cout << "[3] GrandChild.igrandchild = " << (int)pVtab[3] << endl;
return 0;
}
从结果我们可以发现,类都会将它的所以虚函数指针放到虚函数列表中。_vfptr是虚指针,指向虚函数地址数组
参考:
http://blog.163.com/xychenbaihu@yeah/blog/static/132229655201210121619750/