0

我是一名初级程序员,刚刚开始使用类和对象,所以请原谅我造成的混乱。

此函数的目的是检查用户名文件是否存在,如果存在则将用户名返回给 main.cpp,以便我可以将其存储在 main.cpp 中,并在需要时使用它来更新该特定文件。

根据我目前的研究,您无法返回字符串或字符数组,从他们建议使用向量代替的类似案例中,这对我来说是正确的路径还是有其他解决方案?我也知道到目前为止我已经使用了 void 并且没有返回类型(用于测试目的)。//登录类文件

void Login::UserSelectLogin()
{
    Draw Gotoxy;
    Draw ObjectLogin;
    Draw ObjectBorder;

    string password;
    string userName;
    bool loginSucceed;

    do
    {
        system("CLS");
        ObjectBorder.Border();
        ObjectLogin.Login();

        //USER INPUTS
        Gotoxy.gotoxy(27, 6);
        cin >> userName;
        Gotoxy.gotoxy(27, 7);
        cin >> password;

        if (ifstream(userName))
            return userName;
        else
        {
            Gotoxy.gotoxy(30, 8);
            cout << "USER ALREADY EXISTS";
            loginSucceed = false;
            _getch();
        }
    } while (loginSucceed != true);

}

//头文件

#ifndef LOGIN_H
#define LOGIN_H
#include <string>

class Login
{
public:
    Login();
    string UserSelectLogin();
    void UserSelectNewUser();
};
#endif

//main.cpp

int main()
{
    SetWindow(80, 22);
    Draw ObjectBorder;
    Draw ObjectLoginOrNewUser;
    Draw ObjectLogin;
    Draw ObjectNewUser;
    Draw ObjectOptionsMenu;
    Draw ObjectMap;
    Draw ObjectBattleScreen;
    Draw ObjectGotoxy;

    Login LoginUser;
    Login CreateNewUser;

    string userName;

    char firstScreenChoice;

    bool gameQuit = false;
    do
    {
        ObjectBorder.Border();
        ObjectLoginOrNewUser.LoginOrNewUser();

        firstScreenChoice = _getch();
        switch (firstScreenChoice)
        {
        case '1':
            userName = LoginUser.UserSelectLogin();
            _getch();
            break;
        case '2':
            CreateNewUser.UserSelectNewUser();
            _getch();
            break;
        default:
            system("CLS");
            ObjectBorder.Border();
            cout << "INVALID INPUT";
            _getch();
        }
        system("CLS");
    } while (gameQuit != true);
}
4

2 回答 2

2

您可以按值返回字符串。只需声明函数返回 astd::string并在函数中使用类似的东西return userName;

于 2015-11-13T23:33:40.400 回答
0

如果存在用户名文件,则将用户名返回给 main.cpp,以便我可以将其存储在 main.cpp 中,并在需要时使用它来更新该特定文件。

您可能会考虑将字符串 userName 移动为形式参数(通过引用传递)...

void Login::UserSelectLogin(std::string& userName)
{
   ...

不需要返回用户名(您的代码缺少返回类型)

注意:当登录失败时,您可能应该确保 userName.size() 为 0。(即设置为空字符串)

userName = "";

更新:使用说明

使用上面的声明,以及类似的实现:

void Login::UserSelectLogin(std::string& userName){ /*..implementation..*/ };

然后,在 main 或任何函数中,您将调用:

 // assume
 Login  aLogin; // default ctor
 // ... 

 // ... time to fetch login name
 std::string aUserName;  // default ctor creates null string
 aLogin.UserSelectLogin(aUserName);  // formal parameter is local var
 // ... continue
于 2015-11-14T00:01:35.460 回答