继承中的多继承
#include<iostream>using namespace std;class Base1
{
public:Base1(){m_A = 10;}
public:int m_A;};class Base2
{
public:Base2(){m_A = 10;}
public:int m_B;int m_A;};class Son :public Base1, public Base2
{public:int m_C;int m_D;
};void test01()
{cout << sizeof(Son) << endl;Son s1;//s1.m_A//二义性cout << s1.Base1::m_A << endl; //解决二义性,加作用域
}int main()
{test01();system("pause");return 0;
}
菱形继承
- 解决问题利用虚基类
sheeptuo内部结构
- vbptr虚基类指针
- 指向一张 虚基类表
- 通过表找到偏移量
- 找到共有的数据
#include<iostream>using namespace std;class Animal
{
public:int m_Age;
};//虚基类 Sheep
class Sheep :virtual public Animal
{};//虚基类 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;cout << st.Tuo::m_Age << endl;cout << st.m_Age << endl; //可以直接访问,原因已经没有二义性的可能了,只有一份m_A
}void test02()
{SheepTuo st;st.m_Age = 100;//找到sheep的偏移量cout << *(int *)((int *)*(int*)&st + 1) << endl;//找到Tuo的偏移量cout << *((int *)((int *)* ((int *)&st + 1) + 1)) << endl;//输出Agecout<<((Animal *)((char *)&st + *(int *)((int *)*(int*)&st + 1)))->m_Age << endl;}int main()
{//test01();test02();system("pause");return 0;
}