菱形继承会导致出现两份数据,造成空间浪费,使用虚继承可以使数据只有一份
#include<iostream>
#include<string>
using namespace std;
class animal{
public:
int m_age;
};
//利用虚继承解决菱形继承的问题
//再继承前加virtual为虚继承
//animal被称为虚基类
class sheep:virtual public animal{};
class tuo:virtual public animal{};
class sheeptuo:public sheep,public tuo{};
void test1() {
sheeptuo st;
//当菱形继承时,两个父类具有相同数据,需要加作用域区分
st.sheep::m_age = 18;
st.tuo::m_age = 28;
cout << "st.sheep::m_age = " << st.sheep::m_age << endl;
cout << "st.tuo::m_age = " << st.tuo::m_age<<endl;
cout << "st.m_age = " << st.m_age << endl;
//菱形数据导致数据有两份,导致浪费
}
int main() {
test1();
system("pause");
return 0;
}
//继承的时候继承虚基类指针,指针指向虚基类表,数据只有一份