13th Week Item 1-animals so called (3)

Source: Internet
Author: User

3, each animal derived class has a "first name" data member, this common member can be fully provided by the base class to transform the above program, the data member as an abstract class animal data members are used by the derived classes.

Code:

#include <iostream> #include <cstring> using namespace std;

Class Animal {protected:string name; Public:animal (string N): Name (n) {} virtual void cry () = 0;}; Class Mouse:public Animal {Private:char sex; Public:mouse (string N,char s): Animal (n), sex (s) {} virtual Voi
        D Cry () {cout<< "I call" <<name<< ", is a";
        if (sex== ' m ') cout<< "male";
        else cout<< "female"; cout<< "The mouse, My cry is: Squeak Squeak."
    "<<endl;

}
}; Class Cat:public Animal {Public:cat (string n): Animal (n) {} virtual void Cry () {cout<< "My name" &lt ;<name<< ", is a cat, my Cry is: Meow meow meow.
    "<<endl;

}
}; Class Dog:public Animal {Public:dog (string n): Animal (n) {} virtual void Cry () {cout<< "My name" &lt ;<name<< ", is a dog, my cry is: Wang Bark.
    "<<endl;

}
};  Class Giraffe:public Animal {Private:char sex; Public:giraffe (string N,char s): Animal (n), sex (s) {} virtual
  void Cry ()  {cout<< "My name is" <<name<< ", is one";
        if (sex== ' m ') cout<< "male";
        else cout<< "female"; cout<< "Giraffes, my neck is too long to make a sound."
    "<<endl;

}
};
    int main () {Animal *p;
    Mouse M1 ("Jerry", ' m ');
    p=&m1;
    P->cry ();
    Mouse m2 ("Jemmy", ' f ');
    p=&m2;
    P->cry ();
    Cat C1 ("Tom");
    p=&c1;
    P->cry ();
    Dog D1 ("Droopy");
    p=&d1;
    P->cry ();
    Giraffe G1 ("Gill", ' m ');
    p=&g1;
    P->cry ();
return 0;
 }


Run Result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.