设计一个Dog类,包含name、age、sex和weight等属性,在有参数的构造函数中对数据成员进行初始化。
公有成员函数有:GetName()、GetAge()、GetSex()和GetWeight()可获取名字、年龄、性别和体重。编写成员函数speak() 显示狗的叫声(Arf!Arf!)。编写主函数,输入狗的名字、年龄、性别和体重;声明Dog对象并用输入的数据通过构造函数初始化对象,通过成员函数获取狗的属性并显示出来。
输入:狗的信息,例如Tom 4 m 2.4
输出:
狗的信息,外加叫声
例如:
Tom
4
m
2.4
Arf!Arf!
代码实现部分:
#include <iostream>
#include <string>
using namespace std;
class Dog
{
string name;
int age;
string sex;
double weight;
public:
Dog(string a,int b,string c,double d):name(a),age(b),sex(c),weight(d) {}
void GetName()//获取狗的名字
{
cout<<name<<endl;
}
void GetAge()//获取狗的年龄
{
cout<<age<<endl;
}
void GetSex()//获取狗的性别
{
cout<<sex<<endl;
}
void GetWeight()//获取狗的体重
{
cout<<weight<<endl;
}
void speak()//狗叫两声
{
cout<<"Arf!Arf!"<<endl;
}
};
int main()
{
string name;
int age;
string sex;
double weight;
cin>>name;
cin>>age;
cin>>sex;
cin>>weight;
Dog D(name,age,sex,weight);
D.GetName();
D.GetAge();
D.GetSex();
D.GetWeight();
D.speak();
return 0;
}