多继承的基本概念
一个类由多个类共同派生被称为多继承。
多继承的格式:
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;
}
多继承总结:
子类由多个父类共同派生,子类调用调用构造函数顺序,肯是最后调用自己,对于多个父类的构造函数顺序的调用,和初始化列表的书写顺序无关,和继承的时候顺序有关。
当多个父类中有同名同类型的函数,子类对象调用该函数时,需要表明哪个类的,加上类名和作用域限定符。