我需要实例化一个 SpriteWithTimer
类,并且新对象将其自身添加到 vector vsprites
中。
这是一个代码片段:
#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>>
谢谢!
最佳答案
存储在 vector 中的对象始终是一个全新的单独构造的对象。因此,您无法将在其他地方创建的对象存储到 vector 。或者,您可以存储:
- 该对象的拷贝:
push_back(*this)
, - 一个对象,内容已从该对象移走:
push_back(std::move(*this))
, - 指向该对象的指针
push_back(this)
。
您需要选择适合您情况的内容。在第三种情况下,请注意悬空指针。基本上,您应该保证所指向对象的生命周期在使用这些指针之前不会结束。
关于c++ - 实例如何将自身添加到 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64800553/