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

5185

被折叠的 条评论
为什么被折叠?



