问题及代码:
/*
* Copyright (c) 2014, 烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:郝俊宇
* 完成日期:2015年 6 月1 日
* 版 本 号:v1.0
* 问题描述:3、每一个Animal的派生类都有一个“名字”数据成员,这个成员设置为基类Animal的成员更好。改造上面的程序,将“名字”成员作为抽象类Animal数据成员被各派生类使用。
* 输入描述:无
* 程序输出:对应的内容
*/
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
class Animal
{
public:
virtual void cry()=0;
Animal(string n=0):name(n){}
protected:
string name;
};
class Mouse:public Animal
{
public:
Mouse(string n=0,char s=0):Animal(n),sex(s){}
void cry()
{
cout<<"我叫"<<name<<",是一只";
if(sex=='f')
cout<<"女老鼠";
else
cout<<"男老鼠";
cout<<",我的叫声是:吱吱吱!"<<endl;
}
private:
char sex;
};
class Cat:public Animal
{
public:
Cat(string n=0):Animal(n){}
void cry()
{
cout<<"我叫"<<name<<",是一只猫,我的叫声是:喵喵喵!"<<endl;
}
};
class Dog:public Animal
{
public:
Dog(string n=0):Animal(n){}
void cry()
{
cout<<"我叫"<<name<<",是一条狗,我的叫声是:汪汪汪!"<<endl;
}
};
class Giraffe:public Animal
{
public:
Giraffe(string n=0,char s=0):Animal(n),sex(s){}
void cry()
{
cout<<"我叫"<<name<<",是";
if(sex=='f')
cout<<"女长颈鹿";
else
cout<<"男长颈鹿";
cout<<",我的脖子太长,发不出声音来!"<<endl;
}
private:
char sex;
};
int main( )
{
cout<<"不知哪种动物,让我如何学叫?"<<endl;
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;
}
运行结果:
知识点总结:
抽象类中的数据成员被派生来使用。
学习心得:
第一次编译的时候出现了4个错误,看了半天不知道是哪里出错了,由于英语渣到不行,就百度了一下提示出错句子的意思,顺便看到了出现这个错误的原因,就按照提示改了一下,在编译就对了。