帮助处理 C++ 中的对象
我的代码
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;
}
编译得很好,但是,当我尝试将“ogre.isalive”(位于代码的最底部)设置为 false 时,没有任何反应并且代码不断循环。我做错了什么?
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;
}
which 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您在循环条件中有赋值 (
ogre.isalive = true
)。应该是:You have assignment (
ogre.isalive = true
) in the loop condition. It should be:使用
或只是
编辑:使用
只是在循环的每个步骤上分配
true
,这样你的while
将永远不会停止。Use
Or just
EDIT: Using
just assigns
true
on each step of the loop, this way yourwhile
will never stop.你的 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:
You want to check for equality:
Or better yet, since the variable is already a boolean:
是一个作业! while 循环将始终运行,因为赋值的结果始终为 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