jeudi 22 février 2018

Perform an input check and initialise an object in C++

I have an example code for asking the user for making an animal by user input but the check is in the if-else construction and the compiler gives me error "error: 'animal' was not declared in the scope". Here is my code. Please suggest how can I work it around.

class Animal{
public:
    string getName(){
        return myName;
    }
     void setName(string name){
        myName = name;
    }
    virtual string Sound()
    {

    }
private:
    string myName;
};
class Cat : public Animal{
public:
    string Sound(){
        return "Myau!\n";
    }
};
class Dog : public Animal{
public:
    string Sound(){
        return "Bark!\n";
    }
};
int main() {

    string type, name;
    cout<<"Vyvedete jivotno:\n 1. Cat\n2. Dog\nJivotno:";
    cin>>type;
    cout<<"\nVyvedete ime:";
    cin>>name;
    if(type == "Cat")
    {
        Cat animal;
    }
    else if(type == "Dog")
    {
        Dog animal;
    }

    animal.setName(name);
    cout<<"My name is "<<animal.getName()<<endl;
    cout<<animal.Sound()<<endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire