以下是我的前向声明代码的示例:
void Register();
void Menu();
void Register()
{
string username, password, hospitalname;
ofstream file;
file.open("Hospital Creds.txt");
cout << "Hospital Name: ";
cin >> hospitalname;
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
cout << endl;
file << hospitalname << endl;
file << username << endl;
file << password << endl;
system("pause");
system("cls");
Menu();
}
void Menu()
{
int choice;
cout << " 1. Register Hospital " << endl;
cout << " 2. Register Donor " << endl;
cout << " 3. Exit " << endl;
cout << endl;
cout << "Please enter a number of your choice: ";
cin >> choice;
switch (choice)
{
case 1:
system("cls");
Register();
break;
}
}
void main()
{
Menu();
}
就像这样,当程序运行时,它进入Menu(),然后选中时,它进入Register(),但是当它想要回调函数Menu()时,程序退出。它出什么问题了?
如果你从Menu()
调用Register()
,那么调用链永远不会结束。该函数嵌套太深。你很快就搞砸了调用堆栈。
实际上,当我编写菜单系统时,我从不从任何函数调用前一级函数。相反,我使用循环无限地运行主菜单,所以我可以像树一样保持我的函数调用关系。
void Sub1() {
// Prompt for input
if (option == 0) {
return; // End the call tree
}
else if (option == 1) {
Sub11();
}
else if (option == 2) {
Sub12();
}
...
}
int MainMenu() {
// Prompt for input
if (option == 0) {
return 0; // Quit program
}
else if (option == 1) {
Sub1();
}
else if (option == 2) {
Sub2();
}
}
....
int main() {
while (MainMenu() != 0);
}
Here是我写的一个示例项目。请注意我如何安排main()
功能。