要求:
写一个类Fish,有品种和重量两个属性,属性的类型自己选择,要求属性封装。
写一个类Cat,Cat中有一个公有的成员函数:
Fish& eat(Fish &f);
eat函数的功能要求判断Fish的品种:
●如果品种是“秋刀鱼”,则输出“无论多沉,我都爱吃。”。同时修改Fish &f的重量为0,并作为函数的返回值返回。
●如果品种不是“秋刀鱼”,则判断鱼的重量,若重量大于200,吃鱼输出信息并返回一个重量为0的Fish;若重量小于200,输出信息,不要修改鱼的重量,直接返回鱼的对象。
#include <iostream>
using namespace std;
class Fish
{
private:
string kind; // 品种
int weight; // 重量
public:
Fish(string k,int w):kind(k),
weight(w){}
string get_kind()
{
return kind;
}
void set_kind(string k)
{
kind = k;
}
int get_weight()
{
return weight;
}
void set_weight(int w)
{
weight = w;
}
friend class Cat;
};
class Cat
{
public:
int weight;
int get_weight()
{
return weight;
}
Fish& eat(Fish &f)
{
if(f.get_kind()=="秋刀鱼")
{
cout<<"无论多沉,只要是秋刀鱼,本喵都爱吃"<< endl;
this->weight=0;
}
else
{
if(f.get_weight()>200)
{
cout<<"虽然不是秋刀鱼,但鱼也不小了,本喵勉为其难就吃了吧"<<endl;
this->weight=0;
}
else
{
cout<<"不是秋刀鱼,还这么小,是不是糊弄我猫大人,本喵不吃"<<endl;
this->weight=f.get_weight();
}
}
}
};
int main()
{
while(1)
{
string a;
int b;
cout << "请输入这只鱼的的品种、重量" <<endl;
cin >> a>> b;
Fish d(a,b);
Cat d2;
d2.eat(d);
cout<<"鱼的体重"<<d2.get_weight()<<endl;
}
return 0;
}