我目前正在掌握如何在我的程序中正確實現多個功能,我認爲我有正確的想法,但我只是想澄清。當將某些邏輯放入某個特定函數時,我是否應該處理該函數的結果或將其返回到「主函數」?我意識到這可能是一個模棱兩可的問題,所以我已經在此發佈我的代碼以嘗試和幫助解決問題。處理程序中的多個功能時。如何處理他們的邏輯呢?
該程序只是添加一個字符串的矢量,但我想知道什麼是最好的方法來處理它。
非常感謝你提前。
程序1.
std::vector<std::string> favouriteGames; //Stores favourite games
int menu = 0; //Menu navigation
std::cout << "1: Add Game. 2: Remove Game. 3: List Games. 4: Exit.";
std::cin >> menu;
//Menu
switch (menu)
{
case 1:
favouriteGames.push_back(AddGame());
break;
case 2:
//favouriteGames.erase(RemoveGame);
break;
case 3:
//ListGames();
break;
case 4:
break;
default:
std::cout << "Please enter correct data.";
}
//Add game
std::string AddGame()
{
std::string gameName;
int menu = 0;
std::cout << "Enter name of game you wish to add.";
std::cin >> gameName;
return gameName;
}
計劃2 或者這樣當函數僅處理數據,並且不返回任何東西。
void AddGame(std::vector<std::string> favouriteGames);
int main()
{
std::vector<std::string> favouriteGames; //Stores favourite games
int menu = 0; //Menu navigation
std::cout << "1: Add Game. 2: Remove Game. 3: List Games. 4: Exit.";
std::cin >> menu;
//Menu
switch (menu)
{
case 1:
AddGame(favouriteGames);
break;
case 2:
//favouriteGames.erase(RemoveGame);
break;
case 3:
//ListGames();
break;
case 4:
break;
default:
std::cout << "Please enter correct data.";
}
//Keep Window open
std::string barn;
std::cin >> barn;
return 0;
}
//Add game
void AddGame(std::vector<std::string> favouriteGames)
{
std::string gameName;
int menu = 0;
std::cout << "Enter name of game you wish to add.";
std::cin >> gameName;
favouriteGames.push_back(gameName);
}
聽起來像[Programmers.SE]的工作。 –