现在的位置: 首页 > 综合 > 正文

第十四周 【项目1-动物这样叫】下面是给出的基类Animal声明和main()函数。

2014年09月05日 ⁄ 综合 ⁄ 共 1061字 ⁄ 字号 评论关闭
#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
  virtual void cry()
    {
      cout<<"不知哪种动物,让我如何学叫?"<<endl;
    }
};
class Mouse:public Animal
{
private:
     string name;
     char sex;
public:
     Mouse(string nam,char se):name(nam),sex(se){}
     virtual void cry()
     {
         cout<<"该动物是老鼠,叫声吱吱吱,性别是"<<((sex=='m')?"男":"女")<<"我的名字是"<<name<<endl;
     }

};
class Cat:public Animal
{
private:
     string name;
public:
     Cat(string nam):name(nam){}
     virtual void cry()
     {
         cout<<"该动物是猫,叫声喵喵喵"<<"我的名字是"<<name<<endl;
     }

};
class Dog:public Animal
{
private:
     string name;
public:
     Dog(string nam):name(nam){}
     virtual void cry()
     {
         cout<<"该动物是狗,叫声汪汪汪"<<"我的名字是"<<name<<endl;
     }

};
class Giraffe:public Animal
{
private:
     string name;
     char sex;
public:
     Giraffe(string nam,char se):name(nam),sex(se){};
     virtual void cry()
     {
         cout<<"该动物是长颈鹿,叫声没有,我的性别是"<<((sex=='m')?"男":"女")<<"我的名字是"<<name<<endl;
     }

};
int main( )
{
    Animal *p;
    p = new Animal();
    p->cry();
    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;
}

运行结果

心得体会

开始的时候 竟然在忘了在class声明结束后加分号。。。。结果可想而知 找了好久才找出来自己错在了哪里 以后做题要细心啊!!

抱歉!评论已关闭.