题目
建立一个名为CStudent的类,该类有以下几个属性:学号、姓名、成绩,并为上述属性定义相应的方法。(注意掌握以下成员函数的使用:构造函数和析构函数、复制构造函数,内敛成员函数,带默认形参值的成员函数。)
方法一:用String来保存字符串
#include<iostream>
#include<cstring>
using namespace std;
class CStudent{
private:
string number,name; //numeber表示学号,name表示姓名
double grade;//grade表示成绩
public:
//默认构造函数和有参构造函数的结合
CStudent (string snumber="NULL",string sname="NULL",double sgrade=0);
//复制构造函数
CStudent(const CStudent &p);
//析构函数
~CStudent(){
}
//重置学生信息
void setstudent(string snumber,string sname,double sgrade);
//获取学号
string getnumber(){
return number;
}
//获取学生姓名
string getname(){
return name;
}
//获取学生成绩
double getgrade(){
return grade;
}
};
//默认构造函数和有参构造函数的综合
CStudent::CStudent(string snumber,string sname,double sgrade):number(snumber),name(sname),grade(sgrade){
}
//复制构造函数
CStudent::CStudent(const CStudent &p):number(p.number),name(p.name),grade(p.grade){
}
//重置函数
void CStudent::setstudent(string snumber,string sname,double sgrade)
{
number=snumber;
name=sname;
grade=sgrade;
}
int main()
{
string number,name;
double grade;
cout<<"输入学号:"<<endl;
cin>>number;
cout<<"输入姓名:"<<endl;
cin>>name;
cout<<"输入成绩:"<<endl;
cin>>grade;
CStudent stu;
cout<<"学号:"<<stu.getnumber()<<" "<<"姓名:"<<stu.getname()<<" "<<"成绩:"<<stu.getgrade()<<endl;
stu.setstudent(number,name,grade);
cout<<"学号:"<<stu.getnumber()<<" "<<"姓名:"<<stu.getname()<<" "<<"成绩:"<<stu.getgrade()<<endl;
}
方法一的改进版
#include<iostream>
#include<cstring>
using namespace std;
class CStudent{
private:
string number,name; //numeber表示学号,name表示姓名
double grade;//grade表示成绩
public:
//默认构造函数和有参构造函数的结合
CStudent (string snumber="NULL",string sname="NULL",double sgrade=0);
//复制构造函数
CStudent(const CStudent &p);
//析构函数
~CStudent(){
}
//重置学生信息
void setstudent(string snumber,string sname,double sgrade);
//获取学号
string getnumber(){
return number;
}
//获取学生姓名
string getname(){
return name;
}
//获取学生成绩
double getgrade(){
return grade;
}
};
//默认构造函数和有参构造函数的综合
CStudent::CStudent(string snumber,string sname,double sgrade){
setstudent(snumber,sname,sgrade);//调用成员函数
}
//复制构造函数
CStudent::CStudent(const CStudent &p){
setstudent(p.number,p.name,p.grade);//调用成员函数
}
//重置函数
void CStudent::setstudent(string snumber,string sname,double sgrade)
{
number=snumber;
name=sname;
grade=sgrade;
}
int main()
{
string number,name;
double grade;
cout<<"输入学号:"<<endl;
cin>>number;
cout<<"输入姓名:"<<endl;
cin>>name;
cout<<"输入成绩:"<<endl;
cin>>grade;
CStudent stu;
cout<<"学号:"<<stu.getnumber()<<" "<<"姓名:"<<stu.getname()<<" "<<"成绩:"<<stu.getgrade()<<endl;
stu.setstudent(number,name,grade);
cout<<"学号:"<<stu.getnumber()<<" "<<"姓名:"<<stu.getname()<<" "<<"成绩:"<<stu.getgrade()<<endl;
}