Help with objects in C++
I have the code
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;
}
whi开发者_运维问答ch compiles fine, however, when I try to set "ogre.isalive" (at the very bottom of the code) to false, nothing happens and the code keeps looping. What am I doing wrong?
ogre.isalive = true
is an assignment! The while loop will always run because the result of the assigment is always true. You need ==
to test for equality. Better yet, just use
while(ogre.isalive)
Your while condition is an assignment and then a check of ogre.isalive, which is of course true because you just assigned it:
while(ogre.isalive = true)
You want to check for equality:
while(ogre.isalive == true)
Or better yet, since the variable is already a boolean:
while(ogre.isalive)
Use
vv
while( ogre.isalive == true )
Or just
while( ogre.isalive )
EDIT: Using
v
while( ogre.isalive = true )
just assigns true
on each step of the loop, this way your while
will never stop.
You have assignment (ogre.isalive = true
) in the loop condition. It should be:
while(ogre.isalive)
...
精彩评论