如何理解C++中的继承与虚继承
发表于:2024-09-22 作者:千家信息网编辑
千家信息网最后更新 2024年09月22日,如何理解C++中的继承与虚继承,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。普通的公有继承class test1{public:
千家信息网最后更新 2024年09月22日如何理解C++中的继承与虚继承
如何理解C++中的继承与虚继承,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
普通的公有继承
class test1{public: test1(int i) :num1(i) {}private: int num1;};class test2 : public test1{public: test2(int i,int j) : test1(i), num2(j) { }private: int num2;};void main(){ test2 t2(1,2);}
(test2内存结构)查看内存发现父类在子类的上面
多重继承
在原有的代码基础上增加了test3类
test3类继承了 test2和test1
class test1{public: test1(int i) :num1(i) {}private: int num1;};class test2{public: test2(int i) : num2(i) { }private: int num2;};class test3 :public test2 ,public test1{public: test3(int i, int j,int k) :test1(i), test2(j),num3(k) {}private: int num3;};void main(){ test3 t3(1, 2, 3);}
(test3内存地址 ) 依旧是父类在子类上
但是现在有两个父类为什么test2在test1上?
这和我们的继承顺序有关 我们先继承了test2又继承了test1 更换内存继承顺序 内存的情况也会有所变化
虚继承
class test1{public: test1(int i) :num1(i) {}private: int num1;};class test2: virtual public test1{public: test2(int i,int j) :test1(i), num2(j) { }private: int num2;};void main(){ test2 t2(1, 2);}
(t2的内存) 我们发现虚继承以后父类成员数据在子类成员数据下面了 首地址处莫名其妙多了四字节
这四字节就是我们的虚基类表的地址
跟随虚继承表 其中存储了本类距离父类对象的差值 通过差值能够找到父类对象
我们再看这个内存0x0082fbd8是t2的首地址 0x0082fbe0是父类的位置
0x0082fbd8 - 0x0082fbe0 == 8
就是本类距离父类对象的差值
虚继承(菱形继承)
class test1{public: test1(int i) :num1(i) {}private: int num1;};class test2: virtual public test1{public: test2(int i,int j) :test1(i), num2(j) { }private: int num2;};class test3 :virtual public test1{public: test3(int i, int j) :test1(i), num3(j){}private: int num3;};class test4 :public test2, public test3{public: test4(int i, int j, int k) :test1(i),test2(i,j), test3(i,j),num4(k) { }private: int num4;};void main(){ test4 t4(1, 2,3);}
test4的内存 我们看到 t2和t3都有自己的虚基类表地址 记录了自己和父类的偏移
两个虚基类表的内容
现在我们计算一下 到爷爷类的差值是否正确
0x00FAFD50 - 0x00fafd3c == 14
0x00FAFD50 - 0x00fafd44 == C
关于如何理解C++中的继承与虚继承问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。
内存
地址
差值
子类
对象
问题
C++
两个
内容
字节
就是
成员
数据
更多
顺序
帮助
解答
易行
普通
莫名其妙
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
数据库查两个基因相关性
南京erp软件开发教程
管理软件开发排行
乡镇干部网络安全
数据库结构数值型
软件开发个人发展路径
数据库中怎么插入日期
宽带运营商网络服务器
软件开发在哪个网站上找工作
速达5000在哪打开数据库
亚信科技 产业互联网
美国服务器收费
女生讲网络安全
网络安全 保密
二五零互联网科技有限公司
青岛德伦网络技术
pg数据库查询表分区信息
河南数据网络技术分类设计
云计算在网络安全应用与发展
网络安全团队宣传
南京erp软件开发教程
信息网络安全保密行动
网络安全获奖内容
速达5000在哪打开数据库
互联网企业家华中科技
服务器远程管理卡需要公网ip吗
计算机网络技术单招介绍
开平网络安全有哪些
中国对网络安全重视情况
搭建公司服务器