c++基础语法:虚继承

2020-07-06 05:42:39易采站长站整理

虚继承 的概念的提出主要是为了解决C++多继承的问题,举个最简单的例子:

class animal{
        public :
              void op()
                  {cout << “hello animal” ;}
 };
class tiger : public animal {
        public :
              void tg()
                  {cout << “this is  tiger” ;}
};
class lion : public animal {
        public :
              void lo()
                  {cout << “this is lion” ;}
};
class liger : public tiger, public lion {
        public :
              void lo()
                  {cout << “this is lion” ;}
};
int main()
{
     class liger  oneliger ;
     liger.op() ; 
}

上面的 liger.op() ;会报错,会提示模糊的成员变量,因为tiger和lion中都包含父类animal的op()操作。
此时内存中的oneliger对象布局从低到高是下面这样的:
1、animal的成员变量


2、继承tiger的成员变量
      //包括 op()


3、继承lion的成员变量
     / /也包括op()


4、liger本身的成员变量


PS: 对象在内存中的布局首先是如果有虚函数的话就是虚表,虚表就是指向一个函数指针数组的指针,然后就是成员变量,如果是普通继承则首先是最根父类的成员变量,然后是次父类成员变量,依次而来最后是本身的成员变量[虚继承相反],成员函数被编译成全局函数不存储在对象空间内,需要调用成员函数的时候,通过类名找到相应的函数,然后将对象的this指针传给函数:
比如这样的代码 
CTest     test; 
test.print(); 
编译器在内部将转换为:(伪代码) 
CTest   test; 
CTest_print(   &test   );   //   CTest的print函数转换为:CTest_print(   CTest*   const   this); 
所以这就和普通函数调用差别不大了
实际应该是函数找到对象,即根据this指针

相关文章 大家在看