目的:

A1和A2类中有同名函数func1(),两者派生出类B。现在类B重载了func1(),现证明B中两个vtable中func1()指向新的不同位置,而不是新的相同位置。也即生成了两份重载函数。

过程:

  1. 测试程序
#include <iostream>

using namespace std;

class A1
{
public:

    virtual void func1(){cout<<"A1::func1"<<endl;}
    virtual void func2(){cout<<"A1::func2"<<endl;}
};

class A2
{
public:

    virtual void func3(){cout<<"A2::func3"<<endl;}
};

class B : public A1, public A2
{
public:
    virtual void func1(){cout<<"B::func1"<<endl;}
//    virtual void func2(){cout<<"B::func2"<<endl;}
    virtual void foo1(){ cout<<"B::fool"<<endl;}
};

int main()
{
    cout<<"类B大小:"<<sizeof(B)<<endl;

    A1* pa1 = new A1();
    A2* pa2 = new A2();
    B* pb = new B();

    long* vptr1 = (long*)*(long*)pb;// 指向B的父类A1的虚表指针
    long* vptr2 = (long*)*(long*)((long*)pb+1);// 指向B的父类A2的虚表指针
    typedef void(*Fun)();

    cout<<"每个数组块大小为"<<sizeof(vptr1[0])<<endl;

    Fun f1 = reinterpret_cast<Fun>(vptr1[0]);
    cout<<"vptr1[0]地址=";//<<(int*)vptr1[0]<<endl;
    printf("0x%x\n", vptr1[0]);
    (*f1)();

    Fun f2 = reinterpret_cast<Fun>(vptr1[1]);
    cout<<"vptr1[1]地址=";
    printf("0x%x\n", vptr1[1]);
    (*f2)();

    Fun f3 = reinterpret_cast<Fun>(vptr2[0]);
    cout<<"vptr2[0]地址=";
    printf("0x%x\n", vptr2[0]);
    (*f3)();

    cout<<"pa1:";
    f1 = reinterpret_cast<Fun>(&pa1->func1);
    printf("0x%x\t",f1);
    f2 = reinterpret_cast<Fun>(&pa1->func2);
    printf("0x%x\n",f2);

    cout<<"虚函数:";
    cout<<"pa1:"<<(int*)*(int*)*(int*)(pa1)<<"\t"<<(int*)*(int*)(*(int*)(pa1)+4)<<endl;

    cout<<"虚函数:";
    cout<<"pa2:"<<(int*)*(int*)*(int*)(pa2)<<endl;//<<"\t"<<(int*)*(int*)(*(int*)(pa2)+4)<<endl;

    cout<<"虚函数:";
    cout<<"pb_v1:"<<(int*)*(int*)*(int*)(pb)<<"\t"<<(int*)*(int*)(*(int*)(pb)+4)
        <<"\t"<<(int*)*(int*)(*(int*)(pb)+8)<<"\t"<<(int*)*(int*)(*(int*)(pb)+12)<<endl;

    cout<<"虚函数:";
    cout<<"pb_v2:"<<(int*)vptr2[0]<<endl;

    cout<<"非虚函数:";
    Fun f4 = (Fun)(&pb->foo1);
    printf("0x%x\n", f4);
    (*f4)();

    return 0;
}

测试结果:
在这里插入图片描述
2. 修改A2中的func3()为func1()
测试结果:
父类中有同名虚函数,子类重载了该同名虚函数,那么这两个table都会指向新的不同的位置,而不是指向同一个新位置

结论

  • 重载多继承同名父类虚函数,派生类多个vtable中同名函数指针指向不同位置,说明生成了两份重载函数。

欢迎批评指正!

Logo

华为AI开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐