gpt4 book ai didi

c++ - 一个结构没有在 C++ 中更新它的一个成员变量

转载 作者:行者123 更新时间:2023-11-30 02:56:16 26 4
gpt4 key购买 nike

我有一个结构体和一个结构体游戏。游戏是生物的“ friend ”。在游戏中我有 vector 生物;然后我通过一个名为 addC 的函数向该 vector 添加一个生物 x

void addc (Creature& c){
creatures.push_back(c);
}

现在我在另一个函数“foo”中,它是 struct Game 的公共(public)方法。

void foo (Creature& c){
...
}

在该函数中,我需要从 vector creatures 中找到另一个生物匹配来自生物 c 的一些信息。所以我在 Game 中创建了另一个公共(public)方法 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”成员是否正在更新时,事实证明它不是!我不明白我做错了什么,因为我是通过引用 vector 来插入的。并且我通过引用从 vector 中获取生物。

游戏中的 vector 是这样的

struct Game{
private:
vector<Creature> creatures;
...
}

struct Creature{
private:
char s;
int x; int y;
...
}

任何帮助将不胜感激!

最佳答案

这个声明:

creatures.push_back(c);

c拷贝 存储到您的 vector 中:标准容器具有值语义。如果您需要引用语义,您应该将指针存储到您的 vector 中。

通常使用智能指针 是个好主意,使用哪一个取决于您的应用程序的所有权策略。在这种情况下,根据我从你的问题文本中获得的信息,让 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 类可以向需要访问存储生物的客户端返回非拥有原始指针(或引用)。

关于c++ - 一个结构没有在 C++ 中更新它的一个成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com