微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

多态和容器

如何解决多态和容器

我有一个用作接口的基类 Drawable,并且有几个继承自它的其他类。现在我想创建这些子类的实例并将它们添加到容器中,以便我可以迭代它们并调用 draw 函数

#include <vector>
#include <string>

struct Drawable
{
public:
    std::string name;
    virtual void draw() = 0;
    Drawable() = default;
    virtual ~Drawable(){};
    Drawable(Drawable &other) = default;
    Drawable(Drawable &&other) = default;
    Drawable &operator=(Drawable &&other) = default;
};

bool operator==(const Drawable &lhs,const Drawable &rhs)
{
    return lhs.name == rhs.name;
}

bool operator!=(const Drawable &lhs,const Drawable &rhs)
{
    return !(lhs == rhs);
}

struct Square : public Drawable
{
    std::string name;
    Square(std::string name)
    {
        this->name = name;
    }
    void draw()
    {
        /* Some logic*/
    }
};

int main()
{
    Square reddy("reddy");

    std::vector<Drawable> drawables;

    drawables.push_back(reddy);
}

我收到此错误消息

error: 
      allocating an object of abstract class type 'Drawable'
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);

这是因为 vector 试图为 Drawable 分配空间(它不能,因为它是一个抽象类)。但是我该怎么做呢?我发现的有关多态性的教程都没有涵盖这样的内容。还是我在寻找错误的东西?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。