#include "iostream"
#include<string>
using namespace std;
class Animal
{
public:
virtual void cry() {cout << "不知哪种动物,让我如何学叫?" << endl;}
};
class Mouse : public Animal
{
public:
Mouse(string name)
{
this->name = name;
}
virtual void cry();
private:
string name;
};
class Cat : public Animal
{
public:
Cat(string name)
{
this->name = name;
}
virtual void cry();
private:
string name;
};
class Dog : public Animal
{
public:
Dog(string name)
{
this->name = name;
}
virtual void cry();
private:
string name;
};
class Giraffe : public Animal
{
public:
Giraffe(string name)
{
this->name = name;
}
virtual void cry();
private:
string name;
};
void Mouse::cry()
{
cout << "我叫" << name << ",是一只老鼠,我的叫声是:吱吱吱!" << endl;
}
void Cat::cry()
{
cout << "我叫" << name << ",是一只猫,我的叫声是:喵喵喵!" << endl;
}
void Dog::cry()
{
cout << "我叫" << name << ",是一条狗,我的叫声是:汪汪汪!" << endl;
}
void Giraffe::cry()
{
cout << "我叫" << name << ",是长颈鹿,脖子太长,发不出声音来!" << endl;
}
int main( )
{
Animal *p;
p = new Animal(); p->cry(); //输出: 不知哪种动物,让我如何学叫?(问题出自此处)
Mouse m("Jerry"); p = &m; p->cry(); //输出: 我叫Jerry,是一只老鼠,我的叫声是:吱吱吱!
Cat c("Tom"); p = &c; p->cry(); //输出: 我叫Tom,是一只猫,我的叫声是:喵喵喵!
Dog d("Droopy"); p = &d; p->cry(); //输出: 我叫Droopy,是一条狗,我的叫声是:汪汪汪!
Giraffe g("Gill"); p = &g; p->cry(); //输出: 我叫Gill,是长颈鹿,脖子太长,发不出声音来!
system("pause");
return 0;
}
不知哪种动物,让我如何学叫?
我叫Jerry,是一只老鼠,我的叫声是:吱吱吱!
我叫Tom,是一只猫,我的叫声是:喵喵喵!
我叫Droopy,是一条狗,我的叫声是:汪汪汪!
我叫Gill,是长颈鹿,脖子太长,发不出声音来!
请按任意键继续. . .
第十三周作业2
最新推荐文章于 2022-02-25 21:57:21 发布