如何解决钻石问题的这种歧义



我正在探索钻石问题。我在下面写了代码。但是,它显示了模棱两可的问题。如何解决?在蛇类中没有覆盖方法可以吗?

    #include <iostream>
    class LivingThing {
    protected:
       void breathe()
       {
          std::cout << "I'm breathing as a living thing." << std::endl;
       }
    };
    class Animal : virtual protected LivingThing {
    protected:
       void breathe() {
          std::cout << "I'm breathing as a Animal." << std::endl;
       }
    };
    class Reptile : virtual public LivingThing {
    public:
       void breathe() {
          std::cout << "I'm breathing as a Reptile." << std::endl;
       }
    };
    class Snake : public Animal, public Reptile {
    };
    int main() {
       Snake snake;
       snake.breathe();
       getchar();
       return 0;
    }

这里发生的情况是,AnimalReptile都用自己的版本覆盖LivingThing::breathe()方法。 因此,Snake继承了两个不同的方法,都称为breathe,一个来自它的基类。当你然后写

snake.breathe();

名称breathe含糊不清,因为它可以指Animal::breatheReptile::breathe。例如,您必须明确地告诉应该调用哪个

snake.Reptile::breathe();

这很可能不是您想要的。 breathe()不是虚拟方法。但是,您很可能希望它是一种虚拟方法,在这种情况下,您绝对应该看看虚拟继承如何解决"菱形"(多重继承(歧义?

最新更新