用C++做一个猫吃鱼的函数代码

要求:

写一个类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;
}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值