C++ 要返回if/else语句上的函数吗
请看这段代码,我会解释:C++ 要返回if/else语句上的函数吗,c++,if-statement,void,C++,If Statement,Void,请看这段代码,我会解释: void GameOver() { cout << "\nWelp, you died. Want to try again?" << endl; cin >> choice; if (choice == "Yes" || "yes") { /*This is where I want the code. I want it to go back to the last
void GameOver()
{
cout << "\nWelp, you died. Want to try again?" << endl;
cin >> choice;
if (choice == "Yes" || "yes")
{
/*This is where I want the code. I want it to go back to the last
function that the player was on.*/
}
if (choice == "No" || "no")
{
cout << "Are you sure? The game will start over when you open it back up." << endl;
cin >> choice;
if (choice == "No" || "no")
{
cout << "Well, bye now!" << endl;
usleep(1000000);
exit (EXIT_FAILURE);
}
}
return;
}
void GameOver()
{
不能选择;
如果(选项=“是”| |“是”)
{
/*这就是我想要的代码。我想要它回到最后一个
播放器正在使用的函数*/
}
如果(选项=“否”| |“否”)
{
不能选择;
如果(选项=“否”| |“否”)
{
cout我建议在GameOver
函数中使用一个参数。然后,每次您想去其他地方时,都可以传递不同的参数。例如,从函数1调用GameOver(1)
,从函数2调用GameOver(2)
这是假设从GameOver
返回并在调用函数中执行不同的选项不是一个选项。首先,类似以下的语句:
if (choice == "Yes" || "yes")
if (strcmpi(choice.c_str(), "Yes") == 0)
编码错误,并且将始终计算为true。您需要改用此选项:
if (choice == "Yes" || choice == "yes")
或者更好地使用不区分大小写的比较函数,如下所示:
if (choice == "Yes" || "yes")
if (strcmpi(choice.c_str(), "Yes") == 0)
其次,除非您添加一个输入参数或使用一个全局变量,GameOver()
不知道是谁在调用它。因此您要做的事情首先不属于GameOver()
本身。它属于调用函数。GameOver()
如果用户选择不继续,则退出游戏。这就是它应该做的所有事情。如果游戏不退出,调用函数应决定如何重试。例如:
void GameOver()
{
cout << "\nWelp, you died. Want to try again?" << endl;
cin >> choice;
//if (choice == "Yes" || choice == "yes")
if (strcmpi(choice.c_str(), "Yes") == 0)
return;
cout << "Are you sure? The game will start over when you open it back up." << endl;
cin >> choice;
//if (choice == "No" || choice == "no")
if (strcmpi(choice.c_str(), "No") == 0)
return;
cout << "Well, bye now!" << endl;
usleep(1000000);
exit (EXIT_FAILURE);
}
void FightProcess()
{
...
if (defeated)
{
GameOver();
Town();
return;
}
...
}
或者,使用FightProcess()
循环可能更有意义:
void FightProcess()
{
...
do
{
...
if (won)
break;
GameOver();
...
}
while (true);
...
}
看看当你不把限制性逻辑放在不属于它的地方时,事情是如何变得更加灵活的?或者你可以选择在FightProcess()中触发事件
例如:-
在GameOver()中,您可以查询观测者以查找上一个事件。从void
中,您是指返回void的函数吗?