问题描述
我有一个用作接口的基类 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 (将#修改为@)