简体   繁体   中英

Wrong class function is being called

I have a class called Smartphone that defines a few variables and functions:

class Smartphone : public Computer {

    int contactNum = 0;
    string contacts[15];
    int contactIndex = 0;
public:
    void call();
    void text();
    void addContact();
    void InitalizeContacts();
    void increaseContactNum();
} MotorolaG7;

Then, I have a bunch of if-statements that run the different functions based off of user input:

void RunSmartPhone() {
    string userAction;
    cout << "What would you like to do? (Options: Install OS, Open App, Increase Disk Size, Install App, Call, Text, Add Contact)" << endl;
    getline(cin, userAction); 

    if (userAction == "Install OS" || userAction == "install os") {
        MotorolaG7.installOs();
    }

    if (userAction == "Open App" || userAction == "open app") {
        MotorolaG7.openApp();
    }
    if (userAction == "Increase Disk Size" || userAction == "increase disk size") {
        MotorolaG7.increaseDiskSize();
    }
    if (userAction == "Install App" || userAction == "install app") {
        string userAppName;
        cout << "Enter app name: ";
        getline(cin, userAppName);
        MotorolaG7.installApp(userAppName);
    }

    if (userAction == "Call" || "call") {
        MotorolaG7.call();
    }


    if (userAction == "Text" || "text") {
        MotorolaG7.text();
    }

    if (userAction == "Add Contact") {
        MotorolaG7.addContact();
    }
}

My problem is that if I say "Add Contact", it ends up running the Call function, and if I say "Text", it also ends up running the Call function. Everything else is working fine except for the Text and Add Contact if statements, which both end up running the Call function.

Your if condition is incorrect, it needs to be:

if (userAction == "Call" || userAction == "call") {
 // ...

You've made the same mistake in another if condition. Again, it needs to be:

if (userAction == "Text" || userAction == "text") {
  // ...

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