c++ - 多重继承的模糊解决方法?

标签 c++ multiple-inheritance

我有一个名为 animal 的基类,以及继承自 Animal 的狗和猫。 还有一个名为 dogcat 的多继承类,它继承自 dog 和 cat, 在 Animal 中,我有一种叫做 sleep 的方法。当我想从 dogcat 使用该方法时,出现错误“DogCat::sleep”不明确,我确实理解这个问题,但我在一本书中读到它应该是可能的,当你将 sleep 声明为虚拟时 - 但它不起作用。

这不可能是书错了还是有什么解决方法?

class Animal
{
public:
    Animal(){}

    virtual void sleep()
    {
        cout << "zzzzzzzzz" << endl;
    }
    virtual void eat() = 0;

};

class Dog: public Animal
{
protected:
    Dog(){}

    virtual void eat() override
    {
        cout << "eats dogfood" << endl;
    } 
};

class Cat :public Animal
{
public:
    Cat(){}
    virtual void eat() override
    {
        cout << "eats catfood" << endl;
    }
};

class DogCat : public Dog, public Cat
{
public:
    DogCat(){}
    using Dog::eat;

};

int main(int argc, char** argv) {
    DogCat *DC = new DogCat();
    DC->sleep();//Error
}

最佳答案

你有 diamond problem

enter image description here

The "diamond problem" (sometimes referred to as the "deadly diamond of death"[4]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

所以。现在你有两个 A 实例。解决方案是什么?你有两个:

  1. 在其中一个子类中定义 sleep 操作并调用它:
class Cat :public Animal
{
    public:
        Cat(){}
        virtual void eat() override
        {
            cout << "eats catfood" << endl;
        }

        void sleep()
        {
            Animal::sleep();
        }
};

int main(int argc, char** argv) {
    DogCat *DC = new DogCat();
    DC->Cat::sleep();
}
  1. 像@Asesh 回答的那样使用虚拟继承。问题出在常用方法eat()。你必须覆盖它。

关于c++ - 多重继承的模糊解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39943401/

相关文章:

c++ - R 包开发中加载时设置的正确做法

c++ - 如何理解 char * ch ="123"?

c++ - 带有可选参数的 boost 函数

c++ - 多重继承的派生类 : How to reuse derived functions without repeating calls to base

c# - C#中的多重继承

c++ - 如果键小于第一个映射元素,为什么 unordered_map::equal_range upper_bound 返回 end

c++ - 按特定顺序打印队列

c++ - 嵌入式 C++ 编译器不支持多重继承的实例?

多父方法调用的 Pythonic 方法

c++ - 多重继承不明确的基类