父类默认构造函数由用户然后通过C++输入

parent class default constructor to be enter by user then through C++

本文关键字:C++ 输入 然后 用户 默认 构造函数 父类      更新时间:2023-10-16

int 我的子类,当我使用继承和设置默认值时,: UserAccout("user","pass");是否可以从cin获取输入?

以下是我的代码示例。

我有我的父类

class UserAcct
{
private:
    string  userName;
    string  userPassword;
public:
    UserAcct(string newUserName, string newPassword);       
    ~UserAcct();                                        
};

这是用户Acct.cpp

UserAcct::UserAcct(string newUserName, string newPassword)
{
   userName = newUserName;
   userPassword = newUserName;
}
可以

这么说,这是我的孩子班

class GameSettings : public UserAcct
private:
    ofstream  odataBase("gameSettings.txt", ios::app);
    ifstream  idataBase("gameSettings.txt", ios::app);
    int       settingSet;
public:
    GameSettings(int newSettings);

儿童班.cpp

GameSettings::GameSettings (int newSettings) : UserAcct("user","pass")//this right here
{ 
    settingsSet = newSettings;
} 

附言。由于某种原因,继承不起作用,我不确定为什么。在子类下.cpp在": UserAcct("user","pass");"中的:之前,我收到一个错误说

错误:应为"{"

问题 1:

您可以通过进行函数调用从cin获取输入。

GameSettings::GameSettings (int newSettings) : UserAccout(getUserName(), getPassword()) {}

其中getUserName()可以是GameSettingsstatic成员函数或非成员全局函数。

static std::string getUserName()
{
   std::string name;
   cin >> name;
   return name;
}

getPassword()可以是类似的函数。

问题2:

看到一个编译器错误,因为您以 ; 结束了以下内容。

GameSettings::GameSettings (int newSettings) : UserAccout("user","pass");
                                                                        ^^^

;需要替换为{}和函数主体内部的任何其他内容。

PS您正在使用UserAcctUserAccout。这需要解决。也许你应该把它说出来,以避免将来的混乱。使用 UserAccount

您的实现需要一个主体:

GameSettings::GameSettings (int newSettings) : UserAccout("user","pass") { }