我有一个名为 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
}
最佳答案
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 实例。解决方案是什么?你有两个:
- 在其中一个子类中定义 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(); }
- 像@Asesh 回答的那样使用虚拟继承。问题出在常用方法eat()。你必须覆盖它。
关于c++ - 多重继承的模糊解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39943401/