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

Cannot instantiate abstract class with multiple inheritance c++(无法实例化具有多继承c++的抽象类)
本文介绍了无法实例化具有多继承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;
}

这篇关于无法实例化具有多继承c++的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

socks4 with asynchronous boost::asio(带有异步Boost::ASIO的socks4)
Boost ASIO HTTP client POST(增强ASIO HTTP客户端开机自检)
asio::strandlt;asio::io_context::executor_typegt; vs io_context::strand(Asio::strandlt;asio::io_context::executor_typegt;VS io_CONTEXT::Strand)
What#39;s the difference between asio::io_context and asio::thread_pool?(ASIO::IO_CONTEXT和ASIO::THREAD_POOL有什么区别?)
How to use boost::asio with Linux GPIOs(如何在Linux GPIO中使用Boost::ASIO)
Boost asio io_service vs io_context(增强ASIO io_服务与io_Context)