简体   繁体   English

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

[英]parent class default constructor to be enter by user then through inheritance - C++

int my child class, when I use inheritence and settings the default with : UserAccout("user","pass");在我的子类中,当我使用继承并设置默认值时: UserAccout("user","pass"); Is it possible to get input from cin instead?是否可以从cin获取输入?

Here are my code examples.这是我的代码示例。

I have my parent class我有我的父类

class UserAcct
{
private:
    string  userName;
    string  userPassword;

public:
    UserAcct(string newUserName, string newPassword);       
    ~UserAcct();                                        
};

this is UserAcct.cpp这是 UserAcct.cpp

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

this is my child class so to say这是我的孩子班,可以这么说

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

the child class .cpp子类.cpp

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

ps.附: The inheritence doesnt work for some reason and I'm not sure why.由于某种原因,继承不起作用,我不确定为什么。 Under the child class .cpp before the : in " : UserAcct("user","pass"); " I get an error saying:在“ : UserAcct("user","pass");之前的子类 .cpp 下,我收到一条错误消息

Error: expected a '{'错误:应为“{”

Question 1:问题 1:

You can get the input from cin by making a function call.您可以通过进行函数调用从cin获取输入。

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

Where getUserName() can be a static member function of GameSettings or a non-member global function.其中getUserName()可以是GameSettingsstatic成员函数或非成员全局函数。

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

getPassword() can be a similar function. getPassword()可以是一个类似的函数。

Question 2:问题2:

You are seeing a compiler error since you ended the following with a ;您看到编译器错误,因为您以;结束了以下内容; . .

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

The ; ; needs to be replaced by {} and anything else that goes inside the body of the function.需要替换为{}以及函数体内的任何其他内容。

PS You are using UserAcct and UserAccout . PS您正在使用UserAcctUserAccout That needs to be fixed.那需要修复。 Perhaps you should spell it out to avoid confusion the future.也许你应该把它拼出来以避免将来混淆。 Use UserAccount .使用用户UserAccount

您的实现需要一个主体:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM