[英]A struct is not updating one of its member variables in c++
我有一个struct Creature和一个struct game。 游戏是Creature的“朋友”。 在游戏中我有矢量生物; 然后我向一个名为addC的函数添加一个生物x到该向量
void addc (Creature& c){
creatures.push_back(c);
}
现在我在另一个函数“foo”中,它是struct Game的公共方法。
void foo (Creature& c){
...
}
在该功能中,我需要从矢量生物中找到另一个与生物c中的某些信息相匹配的生物。 所以我在Game中创建了另一个名为fooHelper的公共方法
void fooHelper (char s, int x, int y){
bool found = false;
for (int i = 0; i < creatures.size() && (!found); ++i){
Creature& c = creatures[i];
if (x == c.x && y == c.y){
c.s = s;
found = true;
}
}
}
但是,当我检查第二个生物的“s”成员是否正在更新时,事实证明它不是! 我不明白我做错了什么,因为我推动了对向量的引用。 我从矢量中通过引用得到了这个生物。
游戏中的矢量看起来像这样
struct Game{
private:
vector<Creature> creatures;
...
}
struct Creature{
private:
char s;
int x; int y;
...
}
任何帮助将非常感激!
这个说法:
creatures.push_back(c);
将 c
的副本存储到向量中:标准容器具有值语义 。 如果需要引用语义,则应将指针存储到向量中。
通常使用智能指针是个好主意,使用哪一个取决于应用程序的所有权策略。 在这种情况下,基于我可以从您的问题文本中获得的信息,让Game
成为Game
中所有Creature
的唯一所有者似乎是合理的(因此唯一的对象负责拥有的Creature
的生命周期) ,特别是当它们不再需要时将它们摧毁),所以std::unique_ptr
应该是一个不错的选择:
#include <memory> // For std::unique_ptr
struct Game{
private:
std::vector<std::unique_ptr<Creature>> creatures;
...
};
您的成员函数addc()
将变为:
void addc(std::unique_ptr<Creature> c)
{
creatures.push_back(std::move(c));
}
客户端会以这种方式调用它:
Game g;
// ...
std::unique_ptr<Creature> c(new Creature());
g.addc(std::move(c));
另一方面,你的foohelper()
函数将被重写为这样的东西:
void fooHelper (char s, int x, int y) {
bool found = false;
for (int i = 0; i < creatures.size() && (!found); ++i){
std::unique_ptr<Creature>& c = creatures[i];
if (x == c->x && y == c->y) {
c->s = s;
found = true;
}
}
}
最后,您的类Game
可以将非拥有的原始指针(或引用)返回给需要访问存储的生物的客户端。
当你将生物引用推入向量时,它正在制作副本。 它是“生物”类型的向量,因此它会从您提供的引用中复制它。 一种解决方案是保持生物指针的向量。
编辑 - 这个问题有助于解释事情比我能够更好地解释为什么你不能有一个引用的向量: 为什么我不能做一个引用的向量?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.