class parent{
public:
virtualvoid foo(){cout<<"parent"<<endl}
};
类中的成员 函数是被存储在别的模块中,不占用类的空间大小。
Sizeof(parent)=4
这四个字节是虚函数表----virtual table.
操作步骤如下:
1:int *p=(int*)&pt ,p是指向pt的起始处的int型指针。 *p取得虚函数表指针的值(四个字节)。
2:int*vt=(int*)*p, 将虚函数表指针的值转为虚函数表的指针。
3:vt[n-1]即是第n个虚函数的地址。
代码如下
// v_table.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
using namespace std;
class parent{
public:
virtual void foo1()
{
cout<<"base_calss1"<<endl;
}
virtual void foo2()
{
cout<<"base_calss2"<<endl;
}
virtual void foo3()
{
cout<<"base_calss3"<<endl;
}
};
typedef void(*func)();
func fp=NULL;
int main(int argc, char* argv[])
{
parent pt;
int *p=(int*)&pt;
int *vt=(int*)*p;
fp=(func)vt[2];
fp();
printf("Hello World!\n");
return 0;
}
多态发生时,每个参与的对象都有虚函数表:
如果子类中没有重写父类的虚函数,则子类的虚函数表中的函数地址和父类一样
如果子类有重写父类的虚函数,则子类虚函数表中的被重写函数的地址变为子类的地址,其余不变。
如果子类有增加虚函数,则虚函数表加载已存在的表后面。
多重继承的子类拥有每个父类的虚函数表。