简体   繁体   中英

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"); Is it possible to get input from cin instead?

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::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

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

Error: expected a '{'

Question 1:

You can get the input from cin by making a function call.

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

Where getUserName() can be a static member function of GameSettings or a non-member global function.

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

getPassword() can be a similar function.

Question 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 . That needs to be fixed. Perhaps you should spell it out to avoid confusion the future. Use UserAccount .

您的实现需要一个主体:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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