如何使函数“运行”工作。该程序只是在运行被调用时退出

时间:2019-07-14 14:13:59

标签: c++ oop

我正在尝试创建一个用于Challenge(自身)的登录系统,但是返回函数的函数“ run”在调用时退出。请协助

#include <iostream>
#include <string>
#include <array>
#include <vector>

using namespace std;
//initialise function pointer that is void and takes no parameter
typedef void (*funcpointer)();
//forward declare a function run that takes an integer parameter
funcpointer run(int op);
//declare class user with username and password
class User {
private:
    string m_name;
    string m_password;

public:
    //constructor for class
    User()
    {
    }
    //friend functions that need to access class members
    friend istream& operator>>(istream& in, User& user);
    friend ostream& operator<<(ostream& out, User& user);
    friend void access();
    friend void display();
};
//vector that stores class
std::vector<User> m_user;
//allows user defined input of class members
istream& operator>>(istream& in, User& user)
{
    cout << "Enter your username: ";
    in >> user.m_name;
    cout << "Enter your password: ";
    in >> user.m_password;
    return in;
}
//ouputs Class member contents in user defined manner(allows cout << class)
ostream& operator<<(ostream& out, User& user)
{
    out << "Username is: " << user.m_name << " Password is: " << user.m_password << '\n';
    return out;
}
//allows user to choose whether to log in, make ne user or view users
void logIn()
{
    int num;
    cout << "Would you like to: \n1: Make new user\n2: Log In\n3: Display users\n";
    do {
        cin >> num;
    } while ((num != 1) && (num != 2) && (num != 3));

    run(num);
}
void newUser()
{
    User x;
    cin >> x;
    m_user.push_back(x);
}
void access()
{

    string name, password;
    cout << "Enter username: ";
    getline(cin, name);

    for (size_t i = 0; i < m_user.size(); i++) {
        if (name == m_user[i].m_name) {
            cout << m_user[i].m_name << " found. Enter password: ";
            getline(cin, password);
            if (password == m_user[i].m_password) {
                cout << "access granted";
            }
            else
                cout << "Wrong password\n";
        }
        else
            cout << "Username not found!\n";
    }
}
void display()
{
    int count = 1;
    for (auto& users : m_user) {
        cout << count << ": " << users.m_name << '\n';
    }
}
//function run that returns function
funcpointer run(int op)
{
    switch (op) {
    default:
    case 1:
        return newUser;
    case 2:
        return access;
    case 3:
        return display;
    }
}

int main()
{

    logIn();

    return 0;
}

我希望传递给1的函数num调用newUser,但以0退出 可能是什么问题呢?我还尝试将参数更改为char和string,结果相同

1 个答案:

答案 0 :(得分:0)

如果返回funcpointer,则可能要调用它。您可以通过在像这样的run(num)();

的funcpointer对象之后写入()来实现