实例化从其他具有抽象方法的类的类时,出现编译器错误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'
我做错了什么?
非常感谢您
哈维尔
答案 0 :(得分:5)
A
中有3个不同的E
对象,您忘记将继承标记为虚拟,因此使用了相同的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;
}