您的位置:首页 > 其它

13周任务2

2012-05-15 20:37 579 查看
#include <iostream>
#include<string>
using namespace std;

class Animal
{
public:
virtual void cry()=0; //{cout<<"不知哪种动物,让我如何学叫?"<<endl;}
Animal(string nam):name(nam){}
protected:string name;
};

class Mouse : public Animal
{
/*private:
string name;*/
public:
Mouse(string nam): Animal(nam){}  ;
virtual void cry() {cout<<"我叫"<<name<<",是一只老鼠,我的叫声是:吱吱!"<<endl;}
};

class Cat : public Animal
{
/*private:
string name; */
public:
Cat(string nam): Animal(nam){}  ;
virtual void cry() {cout<<"我叫"<<name<<",是一只猫,我的叫声是:喵喵!"<<endl;}
};

class Dog : public Animal
{
/*private:
string name;*/
public:
Dog(string nam): Animal(nam){}  ;
virtual void cry() {cout<<"我叫"<<name<<",是一条狗,我的叫声是:汪汪!"<<endl;}
};

class Giraffe : public Animal
{
/*private:
string name; */
public:
Giraffe(string nam):  Animal(nam){}  ;
virtual void 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;
}



 

 


感悟:感觉有虚函数倒是挺好的 ,只要有命令,同名函数就会做出不同的反应,比分别定义各自的函数效率提高了很多。。。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息