所以我有一个结构,它保存游戏中实体的变量(命中点、x和y坐标等(,并且我有全局声明的结构。然而,我在";设置";函数,并希望它们的变量在单独的"函数"中被修改;逻辑";作用但显然,由于这些实例对于";设置";函数;逻辑";函数无法修改其变量。
这是对我当前代码的简化。
// Global space
struct entity {
int hp, atk, x, y;
};
void Setup()
{
entity dummy;
dummy.hp = 10;
dummy.atk = 2;
dummy.x = 5;
dummy.y = 5;
}
void Logic()
{
// if(dummy is attacked)
dummy.hp -= 4;
}
int main()
{
Setup();
while(game is not over)
Logic();
}
有几种不同的方法可以解决这个问题:
- 将
dummy
移动到全局范围:
struct entity {
int hp, atk, x, y;
};
entity dummy;
void Setup()
{
dummy.hp = 10;
dummy.atk = 2;
dummy.x = 5;
dummy.y = 5;
}
void Logic()
{
if (dummy is attacked)
dummy.hp -= 4;
}
int main()
{
Setup();
while (game is not over)
Logic();
}
- 将
dummy
移动到main()
中,然后通过引用(或指针(将其传递到Setup()
和Logic()
:
struct entity {
int hp, atk, x, y;
};
void Setup(entity &e)
{
e.hp = 10;
e.atk = 2;
e.x = 5;
e.y = 5;
}
void Logic(entity &e)
{
if (e is attacked)
e.hp -= 4;
}
int main()
{
entity dummy;
Setup(dummy);
while (game is not over)
Logic(dummy);
}
- 是上面#2的扩展,然后可以将
Setup()
和Logic()
移动到结构本身中:
struct entity {
int hp, atk, x, y;
void Setup();
void Logic();
};
void entity::Setup()
{
hp = 10;
atk = 2;
x = 5;
y = 5;
}
void entity::Logic()
{
if (is attacked)
hp -= 4;
}
int main()
{
entity dummy;
dummy.Setup();
while (game is not over)
dummy.Logic();
}