菱形继承问题的解决办法 —— 虚继承!

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Animal
{
public:
	int m_Age;
};

//虚基类 Sheep
//虚基类并不是在声明基类的时候声明的,而是在声明派生类时,指定继承方式声明的。
//虚继承是声明类时的一种继承方式,在继承属性前面添加virtual关键字。
class Sheep :virtual public Animal  //类Sheep是类Animal的公用派生类;类Animal是类Sheep的虚基类。
{
};
//虚基类 Tuo
class Tuo :virtual public Animal
{
};

class SheepTuo :public Sheep, public Tuo
{

};

//菱形继承的解决方案 利用虚继承  //操作的是共享的一份数据

void test01()
{
	SheepTuo st;
	st.Sheep::m_Age = 10;
	st.Tuo::m_Age = 20;

	cout << st.Sheep::m_Age << endl;  //20
	cout << st.Tuo::m_Age << endl;       //20
	cout << st.m_Age << endl; //可以直接访问,原因已经没有二义性的可能了,只有一份m_Age     //20
}

//通过地址 找到 偏移量
//内部工作原理
void test02()
{
	SheepTuo st;
	st.m_Age = 100;

	//找到Sheep的偏移量操作
	//cout<< *(int *)((int *)*(int *)&st + 1) << endl;

	cout << *(int*)((int*)*(int*)&st + 1) << endl;   //8

	//找到Tuo的偏移量
	cout << *((int *)((int *)*((int *)&st + 1) + 1)) << endl;   //4

	//输出Age
	cout << ((Animal*)((char *)&st + *(int*)((int*)*(int *)&st + 1)))->m_Age << endl;  //100

}

int main(){
	//test01();
	test02();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值