c++ - 如何使功能“运行”工作。调用 run 时程序仅退出
问题描述
我正在尝试为挑战(self)创建一个登录系统(正在进行中),但是返回一个函数的函数“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;
}
我希望函数 num 在传递 1 时调用 newUser ,但会以 0 退出,这可能是什么问题?我也尝试将参数更改为 char 和 string 具有相同的结果
解决方案
如果你返回 funcpointer 你可能想要调用它。您可以通过在这样的 funcpointer 对象之后编写 () 来实现run(num)();
推荐阅读
- node.js - AWS API Gateway“不支持的方法\”未定义\“”作为响应
- php - 使用 php 从数据库中的所有数据创建 json
- python - Python Turtle:是否可以在填充命令中使用图层
- python-3.x - 我可以使用 python 'socket' 模块来监听我的外部 IP 吗?如果没有,是否有预装的模块可以?
- android - Firebase onVerificationCompleted 从 1 月 10 日起不再调用
- java - 读取 csv 文件时 Java 堆错误内存超出范围
- java - 为什么 Room 观察者会一遍又一遍地将同一个实体添加到数据库中?
- java - Xamarin KeyStore PasswordProtection 字段
- javascript - 需要 Babel “^7.0.0-0”,但加载的是“6.26.3”
- go - Golang 频道:超时模式不能作为示例