C++游戏循环中对象成员变量无法持续更新的问题及修复方案
问题根源与修复方案
嘿,我一眼就看出你踩了C++函数参数传递的经典坑!你遇到的问题核心在于:
你在battle函数里用的h参数是按值传递的——每次调用battle时,程序会把gunther.health的值复制一份给h,你在函数里修改的只是这个临时副本,完全没碰过原对象的health成员变量。而Ehealth是类的成员变量,你直接修改的是对象自身的属性,所以它能正常持续递减。
下面给你两种简单的修复方法:
方法一:改用引用传递参数
把battle函数的h参数改成引用类型(int&),这样函数里对h的修改会直接作用到原对象的health上,相当于直接操作原变量:
class card { public: int health, att; char type; int Ehealth = 100; char dec; // 将h改为引用类型int& void battle(int attack, int& h) { cout << "Pick an action: "; cin >> dec; switch (dec) { case 'A': Ehealth -= attack; h -= 5; // 现在修改的是原对象的health break; } cout << "The enemy's health is: " << Ehealth << endl << "Your health is: " << h << endl; } };
主函数的调用代码不用改,这样每次选A后,你的health就会持续递减了。
方法二:直接操作类的成员变量
既然health本身就是card类的成员变量,其实完全没必要把它作为参数传进去。成员函数可以直接访问和修改自身的成员变量,这样代码更简洁,也更符合面向对象的设计逻辑:
class card { public: int health, att; char type; int Ehealth = 100; char dec; // 去掉h参数,直接使用成员变量health void battle(int attack) { cout << "Pick an action: "; cin >> dec; switch (dec) { case 'A': Ehealth -= attack; health -= 5; // 直接修改对象自身的health break; } cout << "The enemy's health is: " << Ehealth << endl << "Your health is: " << health << endl; } }; int main() { card gunther; gunther.health = 150; gunther.att = 5; gunther.type = 'D'; while (1) { gunther.battle(gunther.att); // 只传递attack参数即可 } }
额外小建议
你现在的循环是无限的,建议加个终止条件,比如当health <= 0或者Ehealth <= 0时退出循环,让游戏有结束逻辑,比如:
while (gunther.health > 0 && gunther.Ehealth > 0) { gunther.battle(gunther.att); } if (gunther.health <= 0) { cout << "You lose!" << endl; } else { cout << "You win!" << endl; }
内容的提问来源于stack exchange,提问作者HeapsOfStacks72
相关产品推荐
相关产品推荐

