一、引入iostream、string
#include<iostream>
#include<string>
二、使用命名空间std
using namespace std;
三、创建类Information
方法一(分别进行成员函数声明和成员函数定义 ):
class Information{
public:
string name;
string sex;
int age;
float height;
float weight;
void get(void);
void set(string n,string s,int a,float h,float w);
};
void Information::get(void){
cout<<"NAME:"<<name<<endl;
cout<<"SEX:"<<sex<<endl;
cout<<"AGE:"<<age<<endl;
cout<<"HEIGHT:"<<height<<endl;
cout<<"WEIGHT:"<<weight<<endl;
}
void Information::set(string n,string s,int a,float h,float w){
name=n;
sex=s;
age=a;
height=h;
weight=w;
}
方法二(直接进行成员函数定义 ):
class Information{
public:
string name;
string sex;
int age;
float height;
float weight;
void get(void){
cout<<"NAME:"<<name<<endl;
cout<<"SEX:"<<sex<<endl;
cout<<"AGE:"<<age<<endl;
cout<<"HEIGHT:"<<height<<endl;
cout<<"WEIGHT:"<<weight<<endl;
}
void set(string n,string s,int a,float h,float w){
name=n;
sex=s;
age=a;
height=h;
weight=w;
}
};
四、主函数main
主函数格式(返回1或0):
int main(){
return 0;
}
创建Information实例化对象(对象名建议与类名相似):
Information information;
创建变量:
string name,sex;
int age;
float height,weight;
输入:
cout<<"----------ENTER----------"<<"\n"<<"ENTER NAME:";
cin>>name;
cout<<"ENTER SEX:";
cin>>sex;
cout<<"ENTER AGE:";
cin>>age;
cout<<"ENTER HEIGHT:";
cin>>height;
cout<<"ENTER WEIGHT:";
cin>>weight;
使用对象名调用函数:
information.set(name,sex,age,height,weight);
information.get();
五、完整函数
#include<iostream>
#include<string>
using namespace std;
class Information{
public:
string name;
string sex;
int age;
float height;
float weight;
//方法一
/*void get(void);
void set(string n,string s,int a,float h,float w);*/
//方法二
void get(void){
cout<<"NAME:"<<name<<endl;
cout<<"SEX:"<<sex<<endl;
cout<<"AGE:"<<age<<endl;
cout<<"HEIGHT:"<<height<<endl;
cout<<"WEIGHT:"<<weight<<endl;
}
void set(string n,string s,int a,float h,float w){
name=n;
sex=s;
age=a;
height=h;
weight=w;
}
};
/*void Information::get(void){
cout<<"NAME:"<<name<<endl;
cout<<"SEX:"<<sex<<endl;
cout<<"AGE:"<<age<<endl;
cout<<"HEIGHT:"<<height<<endl;
cout<<"WEIGHT:"<<weight<<endl;
}
void Information::set(string n,string s,int a,float h,float w){
name=n;
sex=s;
age=a;
height=h;
weight=w;
}*/
int main(){
Information information;
string name,sex;
int age;
float height,weight;
cout<<"----------ENTER----------"<<"\n"<<"ENTER NAME:";
cin>>name;
cout<<"ENTER SEX:";
cin>>sex;
cout<<"ENTER AGE:";
cin>>age;
cout<<"ENTER HEIGHT:";
cin>>height;
cout<<"ENTER WEIGHT:";
cin>>weight;
cout<<"----------PRINT----------"<<endl;
information.set(name,sex,age,height,weight);
information.get();
return 0;
}
(注:有更好的方法都可以提出)