C++虚函数表解析【二】

接c++虚函数表解析【一】

如果一个类没有继承关系,且该类中定义了虚函数,那么这个类的实例只有一张虚函数表,如【一】所说明;对于一个单继承的类,即派生类的基类只有一个,如果它有虚函数,也只有一张虚函数表。但是,对于多重继承的类,它可能会有多张虚函数表。下面一一具体说明:

还是以代码为例,看下面代码:

class Base1{
      public:
             Base1(int num):num_1(num){}
             virtual void foo1(){cout<<"Base::foo1"<<num_1<<endl;}
             virtual void foo2(){cout<<"Base::foo2"<<num_1<<endl;}  
             virtual void foo3(){cout<<"Base::foo2"<<num_1<<endl;} 
      private:
              int num_1;  
};
class Base2{
      public:
             Base1(int num):num_2(num){}
             virtual void foo1(){cout<<"Base::foo1"<<num_2<<endl;}
             virtual void foo2(){cout<<"Base::foo2"<<num_2<<endl;}  
             virtual void foo3(){cout<<"Base::foo2"<<num_2<<endl;} 
      private:
              int num_2;  
};
class Base3{
      public:
             Base1(int num):num_3(num){}
             virtual void foo1(){cout<<"Base::foo1"<<num_3<<endl;}
             virtual void foo2(){cout<<"Base::foo2"<<num_3<<endl;}  
             virtual void foo3(){cout<<"Base::foo2"<<num_3<<endl;} 
      private:
              int num_3;  
};
class Derived1:public Base1{
      public:
             Derived(int num):Base1(num){}
             virtual void faa1(){cout<<"Derived1::faa1"<<endl;}//未覆盖Base1中定义的虚函数 
             virtual void faa2(){cout<<"Derived1::faa2"<<endl;}    
      
};
class Derived2:public Base1{
      public:
             Derived2(int num):Base1(num){}
             virtual void foo2(){cout<<"Base::foo2"<<endl;} //只覆盖了Base1::foo2 
             virtual void fbb2(){cout<<"Derived2::fbb2"<<endl;}
             virtual void fbb3(){cout<<"Derived2::fbb3"<<endl;}    
      
};
class Derived3:public Base1,public Base2,public Base3{  //多重继承,无覆盖 
      public:
             Derived3(int num_1,int num_2,int num_3):Base1(num_1),Base2(num_2),Base3(num_3){}
             virtual void fcc1(){cout<<"Derived3::fcc1"<<endl;}
             virtual void fcc2(){cout<<"Derived3::fcc2"<<endl;}    
      
};
class Derived4:public Base1,public Base2,public Base3{  //多重继承,有覆盖 
      public:
             Derived3(int num_1,int num_2,int num_3):Base1(num_1),Base2(num_2),Base3(num_3){}
             virtual void foo1(){cout<<"Derived3::foo1"<<endl;}//覆盖了Base1::fool,Base2::fool,Base::fool 
             virtual void fdd(){cout<<"Derived4::fdd"<<endl;}    
      
};

上面代码说明了四种继承情况下的虚函数表:

1)一般继承(无虚函数覆盖):Derived1类继承自Base1类,Derived1的虚函数表如图1所示。


Derived1类内没有任何覆盖基类Base1的函数,因此虚函数依次被添加到虚函数表中。

C++虚函数表解析【二】_第1张图片

2)一般继承(有虚函数覆盖):Deirved2类继承自Base1类,并对Base1类中的虚函数foo2()进行了覆盖。Derived2的虚函数表如图二所示。


C++虚函数表解析【二】_第2张图片

Derived2覆盖了基类Base1的foo1(),因此其虚函数表中Derived2::foo2()替换了Base::foo2()。

未完待续。

你可能感兴趣的:(C++虚函数表解析【二】)