多重继承二义性

先以一个例子来引入多重继承出现的问题:

#include <iostream>

using namespace std;
class Person
{
  public :
   void sleep(){cout<<"this is a sleep function"<<endl;}
   void eat(){cout<<"this is a eat function"<<endl;}
};
class Author:public Person
{
  public:
   void writeBook(){cout<<"this is a writeBook function"<<endl;}
};
class Coder:public Person
{
  public:
   void writecode(){cout<<"this is a writecode function"<<endl;}
};
class Teacher:public Author,public Coder
{
   
};
int main()
{
    Teacher t;
    t.writeBook();
    t.writecode();
    t.sleep();
    t.eat();
    return 0;

}

这是编译结果:


这里就充分体现了多重继承的缺点,如果派生类所继承的多个基类有相同的基类,而派生类对象需要调用这个祖先类的接口方法,就会容易出现二义性。通常有两种解决方案

1.加上全局符确定调用哪一份拷贝,上述的程序可改为:

    t.Author::sleep();
    t.Author::eat();

2.采用虚拟继承

class Author:virtual public Person

class Coder:virtual public Person

3.虚基类的构造函数和初始化

#include <iostream>
using namespace std;


class base 
{
protected:
  int x;
    public :
       base(int x1){
          x=x1;
          cout<<"base constructor x="<<x<<endl;
       }
};
class base1:virtual public base
{


    int y;
    public :
       base1(int x1,int y1):base(x1){
          y=y1;
          cout<<"base constructor y="<<y<<endl;
       }
};
class base2:virtual public base
{


    int z;
    public :
       base2(int x1,int y1):base(x1){
          z=y1;
          cout<<"base constructor z="<<z<<endl;
       }
};
class user:public base1,public base2
{
   int m;
   public:
   user(int x1,int y1,int z1,int m1):base(x1),base1(x1,y1),base2(x1,z1){
     m=m1;
     cout<<"base constructor m="<<m<<endl;
   }
};
int main()
{
    user t(1,2,3,4);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38211852/article/details/80637954