C ++ - 前向声明不起作用

时间:2017-12-22 04:18:50

标签: c++

以下是我的前向声明代码的示例:

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()时,程序退出。怎么了?

1 个答案:

答案 0 :(得分:3)

如果您从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()函数。

相关问题