C++实现“喂宠物狗“

写一个类Food,有种类和重量两个属性,属性的类型自己选择,要求属性封装。

写一个类Dog,Dog中有一个公有的成员函数:

Food& eat(Food &f);

eat函数的功能要求判断Food的种类:

● 如果食物种类是“肉”或者"罐头",则输出“小狗:“我最爱吃了,我还能吃。”。同时修改Food &f的重量为0,并作为函数的返回值返回。

● 如果食物种类不是“肉”或者"罐头",则判断食物的重量,若重量小于20斤,吃食物输出信息并返回一个重量为0的Food;若重量大于20斤,输出信息,不要修改食物的重量,直接返回食物的对象。

代码编写如下:

#include <iostream>
using namespace std;
//食物
class Food
{
private:
    string kind;//食物种类
    int weight;//种类(斤)
public:
    Food(string kind,int weight)//有参构造函数
    {
        this->kind=kind;
        this->weight=weight;//使用this指针区分重名变量
    }
    int get_weight()//getter可读
    {
        return weight;
    }
    void set_weight(int weight)//setter可写
    {
        this->weight = weight;
    }
    string get_kind()
    {
        return kind;
    }
    void set_kind(string kind)
    {
        this->kind = kind;
    }
};
//狗
class Dog
{
public:
    Food& eat(Food &f)//参数和返回值使用引用
    {
        if(f.get_kind()=="肉"||f.get_kind()=="罐头")
        {
            cout<<"小狗:“我最爱吃了,我还能吃”"<<endl;
            f.set_weight(0);
            return f;//返回值为食物类的对象
        }
        else//其他食物
        {
            if(f.get_weight()<=20)
            {
                cout<<"小狗:吃完了"<<endl;
                f.set_weight(0);
            }
            else
            {
                cout<<"小狗:这些太多了,我不太爱吃,帮我换个少点的吧"<<endl;
                return f;
            }
        }
    }
};

int main()
{
    cout<<"输入你要投喂的食物种类和重量:";
    string kind;
    int weight;
    cin>>kind>>weight;//手动输入食物种类和重量
    Food food(kind,weight);//创建对象,执行完调用自定义的构造函数
    Dog dog;//创建对象
    dog.eat(food);
    cout<<"减肥的小狗饭盆中还剩"<<food.get_weight()<<"斤的"<<food.get_kind();
    return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值