服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Sql Server - c++基础语法:虚继承

c++基础语法:虚继承

2020-01-15 15:35c++教程网 Sql Server

虚继承概念的提出主要是为了解决C++多继承的问题。下面我就为大家列举一个简单的例子

虚继承 的概念的提出主要是为了解决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指针

为了解决 上面多继承的问题,所以c++中提出了虚继承的概念,虚继承就是在子类中只保留一份父类的拷贝,拿上面的类子来说,就是“如果有一份父类的拷贝的话就用父类的拷贝,如果没有就加入一份拷贝” :

复制代码代码如下:

class animal{
        public :
              void op()
                  {cout << "hello animal" ;}
 };
class tiger : public virtual animal {
        public :
              void tg()
                  {cout << "this is  tiger" ;}
};
class lion : public virtual 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对象在内存中的布局就变成了:
4、animal的成员变量

 

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

2、继承lion的成员变量
     //已经包含一份拷贝,所以 已经不包括op()

1、liger本身的成员变量

这样内存中就只有一份animal对象的拷贝,所以就不会存在模糊的问题;

延伸 · 阅读

精彩推荐