繼承中的多繼承
#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;
}
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?