继承中的二义性归属问题

当一个基类产生多个子类,这些子类又产生新的子类时,调用基类的成员函数会产生二义性问题

代码示例

 1 /*          human
 2         /            
 3     mother            father
 4                      /
 5              son
 6 */
 7 #include <iostream>
 8 using namespace std;
 9 class human
10 {
11 public:
12     void stand(){ cout << "hehe" << endl; }
13 };
14 class mother :public human
15 {
16 
17 };
18 class father :public human
19 {
20 
21 };
22 class son :public father, public mother
23 {
24 
25 };
26 int main()
27 {
28     son tom;
29     //tom.stand()//会有二义性,编译器不知道stand()函数是指从mother继承来的还是从father继承来的
30     tom.mother::stand();//指明stand()函数是从mother那里继承来的,用::标识符(成员限定符)
31     return 0;
32 }

结果演示

定义为虚基类可解决二义性问题,不必再添加成员限定符

代码演示

 1 #include <iostream>
 2 using namespace std;
 3 class human
 4 {
 5 public:
 6     void stand(){ cout << "人类能够直立行走" << endl; }
 7 };
 8 class mother :virtual public human   //virtual的意思是虚的,也就是定义虚基类
 9 {
10 
11 };
12 class father :virtual public human  //每个子类都定义虚基类
13 {
14 
15 };
16 class son :public father, public mother
17 {
18 public:
19     
20 };
21 int main()
22 {
23     father mike;
24     mike.stand();
25     mother jane;
26     jane.stand();
27     human man;
28     man.stand();
29     son tom;
30     tom.stand();
31     return 0;
32 }

结果演示

或者是每个类都定义自己的成员函数,函数名可以相同,编译时自动调用

代码示例

 1 #include <iostream>
 2 using namespace std;
 3 class human
 4 {
 5 public:
 6     void stand(){cout<<"人类能够直立行走"<<endl;}
 7 };
 8 class mother:virtual public human
 9 {
10     public:
11     void stand(){cout<<"母类能够直立行走"<<endl;}
12 };
13 class father:virtual public human
14 {
15     public:
16     void stand(){cout<<"父类能够直立行走"<<endl;}
17 };
18 class son:public father,public mother
19 {
20     public:
21     void stand(){cout<<"子类能够直立行走"<<endl;}
22 };
23 int main()
24 {
25     son tom;
26     tom.stand();
27     father mike;
28     mike.stand();
29     mother jane;
30     jane.stand();
31     human man;
32     man.stand();
33     return 0;
34 }

结果演示

原文地址:https://www.cnblogs.com/table/p/4727438.html