【项目1-动物这样叫】
下面是给出的基类Animal声明和main()函数。
1、根据给出的main()函数和运行结果的提示,设计出相关的各个类,注意观察运行结果,提取出每个类中需要的数据成员,并匹配上需要的成员函数。
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:d.cpp
*作 者:张旺华
*完成日期:2015年5月27日
*版 本 号:v1.0
*/
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void cry()
{
cout<<"不知哪种动物,让我如何学叫?"<<endl;
}
};
class Mouse : public Animal
{
public:
Mouse(string n,char a='0'):name(n),sex(a) {}
void cry()
{
cout<<"我叫"<<name<<",是一只";
cout<<((sex=='0')?"":((sex=='m')?"男":"女"));
cout<<"老鼠,我的叫声是:吱吱吱!"<<endl;
}
private:
char sex;
string name;
};
class Dog : public Animal
{
public:
Dog(string n,char a='0'):name(n),sex(a) {}
void cry()
{
cout<<"我叫"<<name<<",是一条";
cout<<((sex=='0')?"":((sex=='m')?"男":"女"));
cout<<"狗,我的叫声是:汪汪汪!"<<endl;
}
private:
char sex;
string name;
};
class Cat: public Animal
{
public:
Cat(string n,char a='0'):name(n),sex(a) {}
void cry()
{
cout<<"我叫"<<name<<",是一只";
cout<<((sex=='0')?"":((sex=='m')?"男":"女"));
cout<<"猫,我的叫声是:喵喵喵!"<<endl;
}
private:
char sex;
string name;
};
class Giraffe : public Animal
{
public:
Giraffe(string n,char a='0'):name(n),sex(a) {}
void cry()
{
cout<<"我叫"<<name<<",是一只";
cout<<((sex=='0')?"":((sex=='m')?"男":"女"));
cout<<"长颈鹿,我的脖子太长,发不出声音来!"<<endl;
}
private:
char sex;
string name;
};
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;
}
知识点应用及心得:
这里有两个地方听力一下:男女的选择输出,姓名性别的初始化。
造成下面结果。
原文:http://blog.csdn.net/wh201458501106/article/details/46045639