** C++继承小猫钓鱼**
##设计一个小猫钓鱼的游戏程序。基本需求如下:
(1)每个小猫有自己的等级(level)和经验分(exp),每累计获得500经验分,就升一级,同时经验分清0;
(2)小猫每次只能钓一条鱼,如果钓上一条章鱼(Octopus),经验分的增加值为 2**章鱼的重量;
如果钓上一条鲸鱼(Whale),经验分增加200;
如果钓上一个金龟(Turtle),则等级直接升一级;
如果钓上来一条鲨鱼(Shark),则等级不变的前提下减经验分(至多减至0),
减少值为5鲨鱼的重量。
请根据上面的模型描述,制定合理的设计方案,请完整定义并实现小猫类,其中类的成员至少要有一个非虚的成员函数CatchFish,用来体现小猫钓鱼的行为过程。同时完整定义并实现其它必要的类。
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
class Fish
{
public:
Fish() {}
Fish(string name)
{
species=name;
}
string GetSpecies()//返回string类型的,就用string
{
return species;
}
int GetWeight()
{
return weight;
}
protected:
string species;
int weight;
};
class Whale:public Fish
{
public:
Whale()
{
species="Whale";
weight=200;
}
};
class Octopus:public Fish
{
public:
Octopus()
{
species="Octopus";
weight=100;
}
Octopus(int w)
{
weight=w;
}
};
class Turtle:public Fish
{
public:
Turtle()
{
species="Turtle" ;
weight=300;
}
};
class Shark:public Fish
{
public:
Shark()
{
species="Shark";
weight=100;
}
};
class Cat:public Fish
{
public:
Cat()
{
level=0;
score=0;
}
Cat(int l,int s)
{
level=l;
score=s;
}
void CatchFish(Fish *f)
{
if(f->GetSpecies()=="Whale")
{
score+=200;
}
else if(f->GetSpecies()=="Octopus")
{
score=score+2*f->GetWeight();
}
else if(f->GetSpecies()=="Shark")
{
int s1;
s1=score-5*f->GetWeight();
if(s1>0)
score=score-5*f->GetWeight();
else score=0;
}
else //Turtle
{
level++;
}
if(score>=500)
{
level=level+1;
score=0;
}
}
void display()
{
cout<<"The level is "<<level<<endl;
cout<<"The score is "<<score<<endl;
}
private:
int level;
int score;
string species;
};
int main()
{
Cat smallcat(0,300);
smallcat.CatchFish(new Octopus());
smallcat.display();
smallcat.CatchFish(new Octopus());
smallcat.display();
smallcat.CatchFish(new Whale());
smallcat.display();
smallcat.CatchFish(new Shark());
smallcat.display();
smallcat.CatchFish(new Whale());
smallcat.display();
smallcat.CatchFish(new Turtle());
smallcat.display();
smallcat.CatchFish(new Whale());
smallcat.display();
return 0;
}
做几点解释:
有些weight题目没有提,是自行定义的。main函数里面也是自行定义的。
团子代码