问题描述:
下面提供了类Stu的数据成员定义,和用于测试的main函数,参考如图的运行结果,完成类的定义,并用多文件形式组织程序
代码:
#include<iostream>
using namespace std;
class Stu
{
private:
string name; //学生姓名
float chinese; //语文成绩
float math; //数学成绩
//接下去写
};
int main()
{
Stu s1,s2;
s1.setStudent("Lin daiyu", 98, 96); //对象置初值
s2.setStudent("Jia baoyu", 90, 88); //对象置初值
s1.show();//打印信息
s2.show();//打印信息
s1.setName("xue baochai");//重新置p1对象的名字
s1.show();
cout<<"s1.Name: "<<s1.getName()<<endl;//打印对象的名字
cout<<"s1.average: "<<s1.average()<<endl;//打印对象的成绩
return 0;
}
解决代码:
#include<iostream>
#include "Stu.h"
#include <string>
using namespace std;
int main()
{
Stu s1,s2;
s1.setStudent("Lin daiyu", 98, 96); //对象置初值
s2.setStudent("Jia baoyu", 90, 88); //对象置初值
s1.show();//打印信息
s2.show();//打印信息
s1.setName("xue baochai");//重新置p1对象的名字
s1.show();
cout<<"s1.Name: "<<s1.getName()<<endl;//打印对象的名字
cout<<"s1.average: "<<s1.average()<<endl;//打印对象的成绩
return 0;
}
#ifndef STU_H
#define STU_H
#include <string>
using namespace std;
class Stu
{
private:
string name; //学生姓名
float chinese; //语文成绩
float math; //数学成绩
public:
void setStudent (string ,float ,float);
void show();
void setName(string );
string getName();
float average();
float sum();
};
#endif // STU_H
#include<iostream>
#include "Stu.h"
#include <string>
using namespace std;
void Stu::setStudent(string a,float b,float c)
{
name=a;
chinese=b;
math=c;
}
float Stu::average()
{
return (chinese+math)/2;
}
float Stu::sum()
{
return chinese+math;
}
void Stu::show()
{
cout<<"Name:\t"<<name;
cout<<"\nScore:\t"<<chinese<<'\t'<<math;
cout<<"\naverage:\t"<<average()<<"\tsum:\t"<<sum()<<'\12'<<'\12';
}
void Stu::setName(string a)
{
name=a;
}
string Stu::getName()
{
return name;
}
运行结果: