使用C++帮助处理对象

aho*_*ota 0 c++ object

我有代码

class ogre
{
    public:
        int health;
        bool isalive;
        string name;
};

int fight()
{
    cout << "You're now fighting an ogre!" << endl;

    ogre ogre;
    player player;
    int ogredamage;
    int playerdamage;

    srand(time(NULL));

    ogre.name = "Fernando Fleshcarver";
    ogre.health = 100;
    ogre.isalive = true;

    player.health = 10000000;
    player.isalive = true;

    while(ogre.isalive = true)
    {
        ogredamage = rand() % 20;
        cout << ogre.name << " deals " << ogredamage << " damage to you!" << endl;
        player.health = player.health - ogredamage;
        cout << "You have " << player.health << " health left." << endl << endl;

        playerdamage = rand() % 20;
        cout << "You deal " << playerdamage << " damage to " << ogre.name << endl;
        ogre.health = ogre.health - playerdamage;
        cout << ogre.name << " has " << ogre.health << " health left." << endl;

        ogre.isalive = false;

    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然而,当我尝试将"ogre.isalive"(在代码的最底部)设置为false时,编译很好,没有任何反应,代码保持循环.我究竟做错了什么?

Ant*_*ony 6

ogre.isalive = true 
Run Code Online (Sandbox Code Playgroud)

是一个任务!while循环将始终运行,因为分配的结果始终为true.你需要==测试是否平等.更好的是,只需使用

while(ogre.isalive)
Run Code Online (Sandbox Code Playgroud)


Ed *_* S. 6

你的while条件是一个赋值,然后检查ogre.isalive,这当然是正确的,因为你刚刚分配它:

while(ogre.isalive = true)
Run Code Online (Sandbox Code Playgroud)

您想要检查是否相等:

while(ogre.isalive == true)
Run Code Online (Sandbox Code Playgroud)

或者更好,因为变量已经是一个布尔值:

while(ogre.isalive)
Run Code Online (Sandbox Code Playgroud)