c++ - 实例如何将自己添加到向量中?
问题描述
我需要实例化一个类SpriteWithTimer
,并且新对象将自身添加到一个 vectorvsprites
中。
这是一个代码片段:
#include <vector>
...
class SpriteWithTimer {
public:
SpriteWithTimer();
~SpriteWithTimer();
...
};
static std::vector<SpriteWithTimer> vsprites;
int main()
{
...
}
...
SpriteWithTimer::SpriteWithTimer(){
...
vsprites.push_back(this);
};
但我有他的错误:
no matching function for call to ‘std::vector<SpriteWithTimer>::push_back(SpriteWithTimer*)’
no instance of overloaded function "std::vector<_Tp, _Alloc>::push_back [with _Tp=SpriteWithTimer, _Alloc=std::allocator<SpriteWithTimer>]" matches the argument list -- argument types are: (SpriteWithTimer *) -- object type is: std::vector<SpriteWithTimer, std::allocator<SpriteWithTimer>>
谢谢!
解决方案
存储在向量中的对象始终是一个全新的单独构造的对象。因此,您不能将在别处创建的对象存储到向量中。或者,您可以存储:
- 该对象的副本:
push_back(*this)
, - 内容从该对象移出的对象:
push_back(std::move(*this))
, - 指向该对象 的指针
push_back(this)
。
您需要选择适合您的情况。在第三种情况下,请注意悬空指针。基本上,您应该保证所指向对象的生命周期在使用这些指针之前不会结束。
推荐阅读
- sql - 计算日期差和返回天数
- google-cloud-logging - 日志保留的增加是否具有追溯力?
- scala - 在 Scala 中读取大型 csv 文件的功能样式
- sql - SQL:选择3个值并计算它们不同的次数
- google-apps-script - 自动 .XLS 到 Google 表格转换器不起作用
- python - 不会返回空白日期行的 Pandas 函数
- optaplanner - 严重过度约束调度的策略
- ios - ionic 5:相机 getPhoto 承诺无结果
- asp.net-core - 如何在 Razor Pages ASP.NET Core 的布局中访问 HostingEnvironment?
- javascript - JavaScript 按箭头函数排序值