c++ - 防止 C++ 中的多重继承

标签 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;
}

说明:有两个名为 Base1 和 Base2 的基类和一个名为 Derived 的派生类。 Derived 是从 Base1 和 Base2 多重继承的。

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

  • 场景 1:派生类:public Base1//好的。---> 没有错误
  • 场景 2:派生类:public Base2//好的。---> 没有错误
  • 场景 3: class Derived : public Base1, public Base2//错误或异常或任何事情。无法继承。

注意:你能回答这个问题吗:我真的不确定这是否可行。还有一件事:这不是菱形继承(钻石问题)。

谢谢。

最佳答案

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

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

class B2 {
   virtual int a() = 0; // note the different return type
};

不可能从两者继承。

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;
}

产生此错误:

  • 错误 C2555:“D::a”:覆盖虚函数返回类型不同,并且与“B1::a”不协变
  • 参见“B1::a”的声明

关于c++ - 防止 C++ 中的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20676637/

相关文章:

c++ - 使用 SWIG 用虚拟方法包装 C++ 类并在 python 中覆盖它们

c++ - QListWidget::setEditTriggers(QAbstractItemView::AnyKeyPressed) 不工作

java - 如何重写父类方法以在该方法的开头和结尾执行某些工作?

java - 继承和对象创建,理论上和实际中

ruby-on-rails - 模型的多重继承

c++ - 为什么在使用之前需要转换通用引用的参数?

c++ - `*' 不能出现在常量表达式中

java - 静态抽象方法解决方法

python - 将行为添加到外部模块返回的对象的 pythonic 方法是什么?

c++ - 多重继承和重复函数调用