无法实例化具有多继承c++的抽象类

实例化从具有抽象方法的其他类继承的类时,遇到编译器错误C2259

继承方案有点奇怪和不透明,但由于问题的一些限制,我需要这样做。

继承方案如下:

class A
{
public:
    enum Animal { CAT, DOG };
    enum Color { RED, GREEN };
    enum Food { MEAT, FISH };

protected:
    virtual Animal animal() const = 0;
    virtual Color color() const = 0;
    virtual Food food() const = 0;
};

class B: public A
{
Animal animal() const { return CAT; }
};

class C: public A
{
Color color() const { return GREEN; }
};

class D: public A
{
Food food() const { return FISH; }
};

然后我声明一个具有多重继承的类,如下所示:

class E : public B, public C, public D
{
};

在这里,当我尝试实例化类E时,收到编译器错误C2259

error C2259: 'E': cannot instantiate abstract class
note: due to following members:
note: 'A::Color A::color(void) const': is abstract
note: see declaration of 'A::color'
note: 'A::Food A::food(void) const': is abstract
note: see declaration of 'A::food'
note: 'A::Animal A::animal(void) const': is abstract
note: see declaration of 'A::animal'

我做错了什么?

非常感谢

哈维尔


解决方案

您在E中有3个不同的A对象,您忘记将继承标记为虚拟,以便使用相同的A对象:

class A
{
public:
    enum Animal { CAT, DOG };
    enum Color { RED, GREEN };
    enum Food { MEAT, FISH };

    virtual ~A(){}

protected:
    virtual Animal animal() const = 0;
    virtual Color color() const = 0;
    virtual Food food() const = 0;
};

class B: public virtual A
{
Animal animal() const override { return CAT; }
};

class C: public virtual A
{
Color color() const override { return GREEN; }
};

class D: public virtual A
{
Food food() const override { return FISH; }
};

class E : public B, public C, public D
{
};

int main()
{
    E e;
}

相关文章