多重継承の基本概念
複数のクラスから派生したクラスを多重継承といいます。
多重継承の形式:
class 类名:继承方式1 类名1,继承方式2 类名2,.....,继承方式n 类名n
{
子类的拓展
};
例:
#include <iostream>
using namespace std;
//封装 沙发的类
class Sofa
{
private:
string sitting;
public:
//无参构造
Sofa() {cout << "沙发的无参构造" << endl;}
//有参构造函数
Sofa(string s):sitting(s)
{
cout << "沙发的有参构造" << endl;
}
void display()
{
cout << sitting << endl;
}
};
//封装 床 类
class Bed
{
private:
string sleep;
public:
//无参
Bed() {cout << "床的无参构造" << endl;}
//有参
Bed(string s):sleep(s)
{
cout << "床的有参构造" << endl;
}
void display()
{
cout << sleep << endl;
}
};
//封装 沙发床类 继承于沙发 和 床
class Sofa_Bed:public Bed,public Sofa
{
private:
int w;
public:
//
Sofa_Bed(){cout << "沙发床的无参构造" << endl;}
//有参构造
Sofa_Bed(string sit, string s, int w):Bed(s),Sofa(sit),w(w)
{
cout << "沙发床的有参构造" << endl;
}
};
int main()
{
Sofa_Bed s;
Sofa_Bed s1("可坐","可躺",123);
s1.Sofa::display();
s1.Bed::display();
return 0;
}
多重継承の概要:
サブクラスは、複数の親クラスから共同して派生します。サブクラスがそのコンストラクターを呼び出す順序は、常にそれ自体を最後に呼び出すものになります。複数の親クラスのコンストラクターが呼び出される順序は、クラスの作成順序とは関係ありません。初期化リストですが、継承時の順序に関係します。
複数の親クラスに同じ名前と型の関数があり、サブクラス オブジェクトがその関数を呼び出すときは、その関数がどのクラスに属しているか、さらにクラス名とスコープ修飾子を示す必要があります。