/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:呼亚萍
* 完成日期:2015年6月1日
* 版 本 号:v1.0
*
* 问题描述: 每一个Animal的派生类都有一个“名字”数据成员,这一共有的成员完全可以由基类提供改造上面的程序,将这一数据成员作为抽象类Animal数据成员被各派生类使用。
* 程序输入:相应的程序
* 程序输出:对应得结果
*/
#include<iostream>
#include<cstring>
using namespace std;
class Animal
{
public:
virtual void cry()=0;
Animal(string na):name(na) {}
protected:
string name;
};
class Mouse:public Animal
{
public:
Mouse(string na,char s):Animal(na),sex(s) {}
void cry();
private:
char sex;
};
void Mouse::cry()
{
if(sex=='m')
cout<<"我叫"<<name<<","<<"我是一只男老鼠,我的叫声是:吱吱吱!"<<endl;
if(sex=='f')
cout<<"我叫"<<name<<","<<"我是一只女老鼠,我的叫声是:吱吱吱!"<<endl;
}
class Cat:public Animal
{
public:
Cat(string na):Animal(na) {}
void cry();
};
void Cat::cry()
{
cout<<"我叫"<<name<<","<<"我是一只猫,我的叫声是:喵喵喵!"<<endl;
}
class Dog:public Animal
{
public:
Dog(string na):Animal(na) {}
void cry();
};
void Dog::cry()
{
cout<<"我叫"<<name<<","<<"我是一条狗,我的叫声是:汪汪汪!"<<endl;
}
class Giraffe:public Animal
{
public:
Giraffe(string na,char s):Animal(na),sex(s) {}
void cry();
private:
char sex;
};
void Giraffe::cry()
{
if(sex=='m')
cout<<"我叫"<<name<<","<<"是男长颈鹿,我的脖子太长,发不出声音来!"<<endl;
if(sex=='f')
cout<<"我叫"<<name<<","<<"是女长颈鹿,我的脖子太长,发不出声音来!"<<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;
}
运算结果:
知识点总结:
增加抽象类中的数据成员,使派生类更加简洁!
学习心得:
随着知识的积累,发现同一个问题有多种不同的解决方法,在解决问题的同时要寻找最棒的解题方法!