首页 > 解决方案 > 实例如何将自己添加到向量中?

问题描述

我需要实例化一个类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>>

谢谢!

标签: c++c++11vector

解决方案


存储在向量中的对象始终是一个全新的单独构造的对象。因此,您不能将在别处创建的对象存储到向量中。或者,您可以存储:

  1. 该对象的副本push_back(*this)
  2. 内容从该对象移出的对象: push_back(std::move(*this)),
  3. 指向该对象 的指针push_back(this)

您需要选择适合您的情况。在第三种情况下,请注意悬空指针。基本上,您应该保证所指向对象的生命周期在使用这些指针之前不会结束。


推荐阅读