持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情
前言
今天笔记的内容是:
- 多继承
什么是多继承?
我们知道,类可以继承另一个类。
但事实上,一个类也可以继承多个类。
比如类x继承了类y,同时又继承了类z。
像这种,一个类同时继承多个类的情况,我们称之为:多重继承(简称为多继承)
多继承的格式
多继承的模糊性
多继承比较受争议。
因为子类继承多个父类时,容易导致成员变量,成员函数同名的情况。
也就是说,多个父类中有同名成员时,会导致子类不知道要使用哪一个成员。
这就产生了歧义,使得子类对该同名成员的引用变得模糊不清。
这就是多继承的模糊性。
因此,对于这种名称冲突问题,我们应该加上类作用域来进行区分。
多继承示例
#include <iostream>
using namespace std;
//基类1
class Aquatic_animals {
public:
int age;
Aquatic_animals() {
this->age = 0;
}
void func() {
cout << "可以在水下生活"<<endl;
}
};
//基类2
class land_animals {
public:
int age;
land_animals() {
this->age = 0;
}
void func() {
cout << "可以在陆地生活" << endl;
}
};
//子类的多继承
class Frog : public Aquatic_animals, public land_animals {
public:
int age;
Frog() {
this->age = 0;
}
void show() {
cout << "可以在陆地和水下生活" << endl;
}
};
int main() {
Frog m;
//m.func(); 报错,由于多继承的模糊性,必须加上作用域
m.Aquatic_animals::func();
m.land_animals::func();
m.show();
return 0;
}
输出结果:
可以在水下生活
可以在陆地生活
可以在陆地和水下生活
如图:
写在最后
好了,今天的笔记就到这里,欢迎大家到评论区一起讨论!