stl vector.push_back()抽象类无法编译 [英] stl vector.push_back() abstract class doesn't compile

查看:127
本文介绍了stl vector.push_back()抽象类无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含类类型为 xx的stl向量。 xx是抽象的。我遇到了这样的问题,当我执行以下操作时,编译器将不允许我实例化:

Let's say I have an stl vector containing class type "xx". xx is abstract. I have run into the issue where the compiler won't let me "instantiate" when i do something like the following:

std::vector<xx> victor;
void pusher(xx& thing)
{
    victor.push_back(thing);
}

void main()
{
    ;
}

我认为这是因为必须调用复制构造函数。通过将xx *存储在向量中而不是xx,我解决了这个问题。有更好的解决方案吗?是什么?

I assume this is because the copy constructor must be called. I have gotten around this issue by storing xx*'s in the vector rather than xx's. Is there a better solution? What is it?

推荐答案

使用 push_back 时,您正在对象的副本并将其存储在向量中。如您所料,这无法正常工作,因为您无法实例化一个抽象类,而该类基本上就是复制构造所要做的。

When you use push_back, you are making a copy of the object and storing it in the vector. As you surmised, this doesn't work since you can't instantiate an abstract class, which is basically what the copy-construction is doing.

建议使用指针,或 boost loki

这篇关于stl vector.push_back()抽象类无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆