使另一个函数可以访问本地结构实例 (C++)

Making a local struct instance accessible to another function (C++)

所以我有一个结构,它保存游戏中实体的变量(命中点、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();
}

有几种不同的方法可以解决这个问题:

  1. 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();
}
  1. 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);
}
  1. 上面#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();
}