C++ 设计Dog类

题目内容:

设计一个Dog类,包含name、age、sex和weight等属性以及对这些属性操作的方法。实现并测试这个类。
根据类的封装性要求,把name、age、sex和weight声明为私有的数据成员,编写公有成员函数setdata()对数据进行初始化,GetName()、GetAge()、GetSex()和GetWeight()获取相应属性。初始化数据由用户输入。


输入格式:

Dog类对象的初始化数据


输出格式:

根据Dog类对象的初始化数据输出一句话,请严格按照格式输出,句末有点号。


输入样例:

ahuang 3 m 2.4


输出样例:

It is my dog.

Its name is ahuang.

It is 3 years old.

It is male.

It is 2.4 kg.

#include<iostream>
#include<string>
using namespace std;
class Dog
{
private:
string name;
int age;
string sex;
float weight;
public:
void setdata(string,int,string,float);
void GetName(){cout<<"Its name is "<<name<<"."<<endl;};
void GetAge(){cout<<"It is "<<age<<" years old."<<endl;};
void GetSex(){cout<<"It is "<<sex<<"."<<endl;};
void GetWeight(){cout<<"It is "<<weight<<" kg."<<endl;};
};
void Dog::setdata(string n,int a,string s,float w)
{
name=n;
age=a;
if(s=="m") sex="male";
else sex="female";
weight=w;
}
int main()
{
Dog dog1;
string n;
int a;
string s;
float w;
cin>>n>>a>>s>>w;
dog1.setdata(n,a,s,w);
cout<<"It is my dog."<<endl;
dog1.GetName();
dog1.GetAge();
dog1.GetSex();
dog1.GetWeight();
return 0;
}

  • 15
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值