多继承的解决方法不明确? [英] Ambiguous workaround for multiinheritance?
问题描述
我有一个称为动物的基类,还有一个从动物继承的狗和猫. 还有一个称为dogcat的多继承类,该类继承自dog和cat, 在动物中,我有一种称为睡眠的方法.当我想从Dogcat中使用该方法时,出现错误"DogCat :: sleep"是模棱两可的,我的确理解该问题,但是当我声明睡眠为虚拟时,我在书中读到它应该是可能的-但它不起作用.
I have a base class called animal, and a dog and a cat that inherit from Animal. And a multiinheritance class called dogcat, that inherit from dog and cat, in Animal i have method called sleep. When i want to use that method from dogcat, i get the error "DogCat::sleep" is ambiguous, i do understand the problem, but i read in a book that it should be possible, when you declare sleep as virtual - but it does not work.
这是不可能的吗,这本书是错误的还是有任何解决方法?
Is this not possible is the book wrong or is there any workaround?
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
}
推荐答案
您遇到了钻石问题
钻石问题"(有时称为致命的死亡钻石" [4])是当两个B类和C类从A继承而D类从B和C继承时产生的歧义.在A中有一个方法B和C已被覆盖,而D没有覆盖它,那么D继承了该方法的哪个版本:B的方法还是C的方法?
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的实例.解决方案是什么?您有两个:
So. Now you have two instances of A. What is it the solution? You have two:
- 在一个小节中定义睡眠操作,并将其命名为:
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();
}
- 使用虚拟继承,例如@Asesh答案.问题是常见的方法eat().您必须覆盖它.
这篇关于多继承的解决方法不明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!