多继承的概念和优缺点
c++
解析:
实际生活中,一些事物往往会拥有两个或两个以上事物的属性,为了解决这个问题,C++引入了多重继承的概念,C++允许为一个派生类指定多个基类,这样的继承结构被称做多重继承。举个例子:
人(Person)可以派生出作家(Author)和程序员(Programmer),然而程序员作者同时拥有作家和程序员的两个属性,即既能编程又能写作,如下图所示。

使用多重继承的例子程序如下:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 
 | #include <iostream>using namespace std;
 
 class Person
 {
 public:
 void sleep() { cout << "sleep" << endl; }
 virtual void eat() { cout << "eat" << endl; }
 };
 
 class Author : public Person
 {
 public:
 void writeBook() { cout << "write Book" << endl; }
 void playGame() { cout << "play Game" << endl; }
 virtual void eat() { cout << "Author eat" << endl; }
 };
 
 class Programmer : public Person
 {
 public:
 void writeCode() { cout << "write Code" << endl; }
 void playGame() { cout << "play Game" << endl; }
 };
 
 class Programmer_Author : public Programmer, public Author
 {
 };
 
 int main()
 {
 Programmer_Author pa;
 
 pa.writeBook();
 pa.writeCode();
 
 
 pa.Author::eat();
 pa.Programmer::eat();
 
 
 system("pause");
 return 0;
 }
 
 | 
输出:
| 12
 3
 4
 
 | write Bookwrite Code
 Author eat
 eat
 
 | 
多重继承的优点很明显,就是对象可以调用多个基类中的接口,如代码34行与代码35行对象pa分别调用Author类的writeBook()函数和Programmer类的writeCode()函数。
多重继承的缺点是什么呢?如果派生类所继承的多个基类有相同的基类,而派生类对象需要调用这个祖先类的接口方法,就会容易出现二义性。代码36、37行就是因为这个原因而出现编译错误的。因为通过多重继承的Programmer_Author类拥有Author类和Programmer类的一份拷贝,而Author类和Programmer类都分别拥有Person类的一份拷贝,所以Programmer_Author类拥有Person类的两份拷贝,在调用Person类的接口时,编译器会不清楚需要调用哪一份拷贝,从而产生错误。对于这个问题通常有两个解决方案:
(1)加上全局符确定调用哪一份拷贝。比如pa.Author::eat()调用属于Author的拷贝。
(2)使用虚拟继承,使得多重继承类Programmer_Author只拥有Person类的一份拷贝。比如在11行和19行的继承语句中加入virtual就可以了。
| 12
 
 |  class Author : virtual public Person         class Programmer : virtual public Person
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | int main(){
 Programmer_Author pa;
 
 pa.writeBook();
 pa.writeCode();
 
 pa.eat();
 pa.Author::eat();
 pa.Programmer::eat();
 pa.Person::eat();
 pa.sleep();
 system("pause");
 return 0;
 }
 
 | 
输出:
| 12
 3
 4
 5
 6
 7
 
 | write Bookwrite Code
 Author eat
 Author eat
 eat
 eat
 sleep
 
 | 
多重继承的概念和优缺点?
答案:
实际生活中,一些事物往往会拥有两个或两个以上事物的属性,为了解决这个问题,C++引入了多重继承的概念。
多重继承的优点是对象可以调用多个基类中的接口。
多重继承的缺点是容易出现继承向上的二义性。
原文地址:https://blog.csdn.net/jandunlab/article/details/14110117