根据类的封装要求,我们可以把name、age、sex和weight声明为公有函数setdata()对数据进行初始化。
#include <iostream>
using namespace std;
class Dog
{
private:
string name;
string age;
string sex;
double weight;
public:
void setdata(sting dogname,int dogage,string dogsex,double dogweight)
{
name = dogname;
age = dogage;
sex = dogsex;
weight = dogweight;
}
string getname()
{
return name;
}
string getage()
{
return age;
}
string getsex()
{
return sex;
}
double getweight
{
return weight;
}
};
int main()
{
Dog dog;
string cinname;
string cinage;
string cinsex;
sting cinweight;
cout<<"请输入小狗的基本信息"<<endl;
cin>>cinname>>cinage>>cinsex>>cinweight;
dog.setdata(cinname,cinage,cinsex,cinweight)
cout<<"小狗的名字为:"<<dog.getname<<endl;
cout<<"小狗的年龄为:"<<dog.getage<<endl;
cout<<"小狗的性别为:"<<dog.getsex<<endl;
cout<<"小狗的体重为:"<<dog.getweight<<endl;
return 0;
}
|