c++基础语法:虚继承
时间:2024-01-23 10:01:00
虚继承 的概念的提出主要是为了解决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对象的拷贝,所以就不会存在模糊的问题;
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP模板引擎Smarty中变量的使用方法示例
python map比for循环快在哪
![](https://img.aspxhome.com/file/2023/7/88997_0s.png)
基于Python实现商场抽奖小系统
![](https://img.aspxhome.com/file/2023/0/131480_0s.jpg)
经验:解决DB2中出现的SQL1032N错误现象
python使用openCV遍历文件夹里所有视频文件并保存成图片
![](https://img.aspxhome.com/file/2023/6/103186_0s.png)
解决Jupyter Notebook开始菜单栏Anaconda下消失的问题
![](https://img.aspxhome.com/file/2023/7/83857_0s.jpg)
如何将你的应用迁移到Python3的三个步骤
vue+echarts封装气泡图的方法
Python实现邮件的批量发送的示例代码
儿童编程python入门
![](https://img.aspxhome.com/file/2023/5/79645_0s.jpg)
javascript读取xml
Python用csv写入文件_消除空余行的方法
带你轻松接触 MySQL中损坏的MyISAM表
python 实现两个npy档案合并
golang程序进度条实现示例详解
![](https://img.aspxhome.com/file/2023/9/134279_0s.png)
用Asp修改注册表
Python常见异常类型处理
JavaScript实现简易购物车最全代码解析(ES6面向对象)
![](https://img.aspxhome.com/file/2023/6/136566_0s.gif)
双向RNN:bidirectional_dynamic_rnn()函数的使用详解
![](https://img.aspxhome.com/file/2023/0/117480_0s.jpg)
python中无法导入本地安装好的第三方库问题
![](https://img.aspxhome.com/file/2023/8/91918_0s.png)