防止C++中的多重继承

him*_*ims 15 c++ inheritance multiple-inheritance

最近我参加了一次C++技术访谈:在那次采访中我问了一个我无法回答的问题:即使我尝试上网和一些论坛但无法得到答案,请参阅下面的代码片段:

using namespace std;

class Base1
{
    public:
    Base1() 
    {
        cout << "Base1 constructor..." << endl;
    }

    ~Base1() 
    {
        cout << "Base1 Destructor..." << endl;
    }
};  

class Base2
{
public:
    Base2() 
    {
        cout << "Base2 constructor..." << endl;
    }

    ~Base2() 
    {
      cout << "Base2 Destructor..." << endl;  
    }
};

class Derived : public Base1, public Base2 
{
public:
  Derived()
  {
      cout << "Derived constructor...."  << endl;
  }
  ~Derived()
  {
      cout << "Derived Destructor..." << endl;
   }
};


int main()
{
   cout << "Hello World" << endl; 
   Base1 b1; Base2 b2;
   Derived d1;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

描述:有两个名为Base1和Base2的基类和一个名为Derived的派生类.Derived是从Base1和Base2继承的多个.

问题:我希望Derived只能从一个类继承,而不是从两个类继承.如果开发人员将尝试从这两个类继承:那么错误应该生成:让我总结一下:

  • Scenerio 1:class Derived:public Base1 // Ok .---> No Error
  • Scenerio 2:类Derived:public Base2 // Ok .---> No Error
  • Scenerio 3:类Derived:public Base1,public Base2 //错误或异常或任何东西.无法继承.

注意:你能否回答这个问题:我真的不确定这是否可行.还有一件事:这不是钻石问题.

谢谢.

egu*_*gur 27

在两个具有不同返回类型的基础中声明纯虚函数:

class B1 {
   virtual void a() = 0;
};

class B2 {
   virtual int a() = 0; // note the different return type
};
Run Code Online (Sandbox Code Playgroud)

从两者都继承是不可能的.

class D : public B1, public B2 {
public:
    // virtual void a() {} // can't implement void a() when int a() is declared and vice versa
    virtual int  a() {}
};

int main(void) {
    D d; // produces C2555 error
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

产生此错误:

  • 错误C2555:'D :: a':覆盖虚函数返回类型不同且与'B1 :: a'不一致
  • 看'B1 :: a'的声明

  • 这回答了关于*direct*继承的直接场景,但仍然以*indirect*继承失败.即,类D1:公共B1`,"类D2:公共B2",最后"类D:公共D1,公共D2"将在D1和D2实现各自的基本纯虚拟时成功编译. (3认同)