Multiple inheritance and pure virtual functions

后端 未结 3 1086
Happy的楠姐
Happy的楠姐 2021-01-04 02:13

The following code:

struct interface_base
{
    virtual void foo() = 0;
};

struct interface : public interface_base
{
    virtual void bar() = 0;
};

struct         


        
3条回答
  •  醉梦人生
    2021-01-04 02:38

    For the case of 'solving' the diamond inheritance problem, the solutions offered by bdonlan are valid. Having said that, you can avoid the diamond-problem with design. Why must every instance of a given class be seen as both classes? Are you ever going to pass this same object to a class that says something like:

    void ConsumeFood(Food *food);
    void ConsumeDrink(Drink *drink);
    
    class NutritionalConsumable {
      float calories() = 0;
      float GetNutritionalValue(NUTRITION_ID nutrition) = 0;
    };
    class Drink : public NutritionalConsumable {
      void Sip() = 0;
    };
    class Food : public NutritionalConsumable {
      void Chew() = 0;
    };
    class Icecream : public Drink, virtual public Food {};
    
    void ConsumeNutrition(NutritionalConsumable *consumable) {
      ConsumeFood(dynamic_cast(food));
      ConsumeDrink(dynamic_cast(drink));
    }
    
    // Or moreso
    void ConsumeIcecream(Icecream *icecream) {
      ConsumeDrink(icecream);
      ConsumeFood(icecream);
    }
    

    Surely it would be better in this case for Icecream to just implement NutritionalConsumable and provide a GetAsDrink() and GetAsFood() method that will return a proxy, purely for the sake of appearing as either food or drink. Otherwise that suggests that there is a method or object that accepts a Food but somehow wants to later see it as a Drink, which can only be achieved with a dynamic_cast, and needn't be the case with a more appropriate design.

提交回复
热议问题