【发布时间】:2021-10-07 04:16:01
【问题描述】:
我在头文件中定义了一个类,并在其中声明了函数,并在单独的 cpp 文件中创建了函数体。然后它在main中没有被识别出来。我已经审查了很多问题,有些在声明中使用了静态这个词,但是当我尝试它时,函数被重新声明,所以它什么也没做,我确保头文件包含在两个 cpp 文件中,但它仍然没有认出来。
#登录注册系统.cpp#
#include <iostream>
#include <cmath>
#include <vector>
#include "L&S functions.h"
using namespace std;
int main()
{
if (status == 1) {
Login(); // this shows an error
cout << "Login";
}
else if (status == 2) {
Register(); // this shows an error
cout << "Register";
}
}
#L&S 函数.h#
#pragma once
#include <string>
using namespace std;
class User {
string username;
string password;
string mail;
public:
void Register();
void Login();
};
#L&S 函数.cpp#
#include <iostream>
#include <cmath>
#include <vector>
#include "L&S functions.h"
using namespace std;
vector<User> people; // initiating vector "people" of type "User"
void User::Register() {
User person; // instantiating a user
cout << "Please choose your username: ";
cin >> User.username; // adds username
cout << "\nPlease set your password: ";
cin >> User.password; // adds password
cout << "\nPlease set your email: ";
cin >> User.mail; // adds email
cout << "\nRegistered successfully!";
people.pushback(person); // adds person to the vector "people"
}
void User::Login() {
string pass; // takes the password typed in to check
string name; // takes the username typed in to check
cout << "Please enter your username: ";
cin >> name;
cout << "\nPlease enter your password: ";
cin >> pass;
for (int i = 0; i < people.size(); i++) { // iterates in the people vector
if (name == username[i] && pass == password[i]) { // look for a match with name and pass
cout << "Welcome " << username[i] << "! Your email is: " << email[i]; // prints "Welcome "username"! Your email is: "email"
}
}
}
【问题讨论】:
-
Login是User对象的非静态成员函数,不是独立函数。你称它为User my_user; my_user.Login();之类的东西也许你的意思是让它成为一个静态函数,或者一个非成员函数。 -
请在这种情况下逐字显示准确的错误。也就是说,您的问题是您试图调用名为
Login和Register的“免费”函数(不在类中),但没有这样的函数。Login和Register是User类的非静态成员函数,因此您需要在调用它们之前创建一个用户对象。