虽然我学过 java,但对 C++ 还是比较陌生。 下面的代码是假设玩家在受到伤害后计算他们的健康状况,假设他们很脆弱。问题是 spellFireDamage 不会降低玩家的生命值,而 poisonDamage 会。我查了一下,知道了重载,但是有两个参数的损坏不能正常工作?这是否与我做错的超载有关?我怎样才能解决这个问题?为什么这对只有一个参数的函数能正常工作?提前致谢
`#include <iostream>
using namespace std;
int damage(int spellsDamage) {
return(spellsDamage*3+5);
}
int damage(int health, int spellsDamage) {
return (health - (spellsDamage*3+5));
}
int main(){
int spellFireDamage = 3;
int spellPoisonDamage = 2;
int playerHealth = 100;
bool playerVulnerable = true;
//do something if vulnerable is true
if (playerVulnerable) {
damage(playerHealth, spellFireDamage);
cout << "player health after fire attack" << endl;
cout << playerHealth << endl;
playerHealth = playerHealth - damage(spellPoisonDamage);
cout << "player health after poison attack" << endl;
cout << playerHealth << endl;
}
else {
cout << "bruh" << endl;
}
return 0;
}
`
如果我只为 spellFireDamage 传递一个参数(如 spellPoisonDamage),它可以正常工作,但我希望我的代码尽可能简单,并且仍然想知道为什么当我传递两个运算符时,我的函数无法正常工作。我抬头看了看,它与引用传递有关,但我不太明白。请解释我如何以最简单/干净的方式解决这个问题!谢谢!
我猜你想要:
void damage(int &health, int spellsDamage) {
health -= spellsDamage * 3 + 5;
}
即该函数的双参数版本应将
health
减少 spellsDamage * 3 + 5
.
但我不会有两个如此相似的函数,尤其是同名函数。只需下定决心让该功能做什么并坚持下去即可。