所以我正在自学 C++ 并完成了这个项目,以测试我对函数的所有知识(我知道其中一些可以使用数组更容易完成,但这不是重点)。它基本上是一个有点美化的石头剪刀布回合制战斗游戏,我已经折叠了下面不太相关的功能。
无论如何,原来的工作正常,但战斗主()非常臃肿(包含整个战斗解决),我想尝试将其分离成它自己的函数。阻止我这样做是因为知道函数只能返回一个变量,但后来我读到了通过引用传递,这应该允许战斗解析修改由战斗主传递给它的参数的值。
但是,这似乎对我不起作用。我不知道我是否只是使用了错误的语法,但似乎只要我尝试通过引用传递,由于重载,函数原型就开始与函数定义发生冲突。有什么建议么?
代码:
#include <iostream>
using namespace std;
bool main();
int main_menu();
bool rules();
int combat_main();
int combat_hero(int,int,int,int);
int combat_nemesis(int,int,int,int);
int combat_resolve(int,int,int,int,int,int);
int combat_end(int,int);
bool main() {...}
int main_menu() {...}
bool rules() {...}
int combat_main() {
int play_again=0;
do {
bool active_battle=1;
cout << "Let the battle begin! Show no mercy!\n" << '\n';
int round_number=0;
int hero_health=5;
int hero_energy=2;
int nemesis_health=5;
int nemesis_energy=2;
do {
if((hero_health<1)||(nemesis_health<1)) {
active_battle=0;
}
//recognizes that battle has ended
else {
++round_number;
cout << "Round " << round_number << '\n' << '\n';
int hero_action= combat_hero(hero_health,hero_energy,nemesis_health,nemesis_energy);
//receives player's choice of action
int nemesis_action= combat_nemesis(hero_health,hero_energy,nemesis_health,nemesis_energy);
//decides AI's choice of action
combat_resolve(hero_action,nemesis_action,hero_health,hero_energy,nemesis_health,nemesis_energy);
//decides round outcome from hero_action and nemesis_action
if(hero_action==0) {
hero_health=0;
//automatically ends battle if player opts to concede defeat
}
}
}
while(active_battle==1);
//cycles combat rounds until one opponent loses
play_again=combat_end(hero_health,nemesis_health);
//prompts player with option to play again at end of battle
}
while(play_again==1);
//repeats if "play again" selected after battle ends
return play_again;
}
int combat_hero(int hero_health,int hero_energy,int nemesis_health,int nemesis_energy) {...}
int combat_nemesis(int hero_health,int hero_energy,int nemesis_health,int nemesis_energy) {...}
int combat_resolve(int hero_action,int nemesis_action,int &hero_health,int &hero_energy,int &nemesis_health,int &nemesis_energy) {...}
int combat_end(int hero_health,int nemesis_health) {...}
编译错误:
1 error LNK2001: unresolved external symbol "int __cdecl combat_resolve(int,int,int,int,int,int)" (?combat_resolve@@YAHHHHHHH@Z)
2 error LNK1120: 1 unresolved externals
3 IntelliSense: more than one instance of overloaded function "combat_resolve" matches the argument list:
function "combat_resolve(int, int, int, int, int, int)"
function "combat_resolve(int hero_action, int nemesis_action, int &hero_health, int &hero_energy, int &nemesis_health, int &nemesis_energy)"
argument types are: (int, int, int, int, int, int)