无锡华诚建设监理有限公司网站,在线建站|网页制作|网站建设平台,新钥匙石家庄网站建设,郑州市做网站的公司同一个类,不同对象使用同一张虚函数表
不同类使用不同的虚函数表
子类自己添加的虚函数(非重写),在VS中是将此放在第一个继承类的虚函数表里.
#include iostream
using namespace std;class Father {
public:virtual void func1() { cout Father::f…同一个类,不同对象使用同一张虚函数表
不同类使用不同的虚函数表
子类自己添加的虚函数(非重写),在VS中是将此放在第一个继承类的虚函数表里.
#include iostream
using namespace std;class Father {
public:virtual void func1() { cout Father::func1 endl; }virtual void func2() { cout Father::func2 endl; }virtual void func3() { cout Father::func3 endl; }void func4() { cout Father::func4 endl;}public:long long x 1;long long y 2;static int z;};class Mother{
public:virtual void handle1() { cout Mother::func1 endl; }virtual void handle2() { cout Mother::func2 endl; }virtual void handle3() { cout Mother::func3 endl; }public:int m 3;int n 4;
};class Son :public Father,public Mother {
public://重写了func1 ,增加了func5virtual void func1() override{ cout Son::func1 endl; }virtual void handle1() { cout Son::handle2 endl; }virtual void func5() { cout Son::func5 endl; }
};class GrandSon :public Son {};typedef void(*func_t) (void); //函数指针 返回类型void ,参数void
int Father::z 1;
int main(void) {Son son;cout 对象地址 (long long *)son endl;long long* vfptr1 (long long*)*(long long*)son; //对象首地址,vfptrcout 第一个虚函数表指针: vfptr1 endl;for (int i 0; i 4; i) {cout 这是第 i 1 个虚函数 endl;((func_t) * (vfptr1 i))();}for (int i 0; i 2; i) {cout *(int *)((long long)son 8 i * 4) endl; //值}long long* vfptr2 (long long*) * ( (long long*)son 3);cout 第二个虚函数表指针: vfptr2 endl;for (int i 0; i 3; i) {cout 这是第 i 1 个虚函数 endl;((func_t) * (vfptr2 i))();}for (int i 0; i 2; i) {cout *(int*)((long long)son 32 i * 4) endl; //值}system(pause);return 0;
} 对象地址00000034A26FF4E8 第一个虚函数表指针:00007FF7095BBD60 这是第1个虚函数 Son::func1 这是第2个虚函数 Father::func2 这是第3个虚函数 Father::func3 这是第4个虚函数 Son::func5 1 0 第二个虚函数表指针:00007FF7095BBD90 这是第1个虚函数 Son::handle2 这是第2个虚函数 Mother::func2 这是第3个虚函数 Mother::func3 3 4 有一个错误:Father的x,y,一开始定义成了int,老师解答,long long * 3 是加3个 long long ,