文件score.dat中保存的是若干名学生的姓名和C++课、高数和英语成绩。
(1)定义学生类,其中包含姓名、C++课、高数和英语成绩及总分数据成员。
(2)用对象数组进行存储学生的成绩,读入成绩并计算总分;将总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中。 讨论:学生人数和总分的另外一种解决方法是用全局变量。但这两种信息与学生有关,是学生类的“属性”,成为学生类的数据成员合适;这两种信息由学生整体决定,用作静态数据成员合适。如不理解这样设计的理由,复习课程前面的相关内容。
代码如下:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include<string>
using namespace std;
//定义学生类
class Student
{
public:
Student(){}
~Student()
{
total_sum-=total;
--stu_num;
}
friend istream& operator >>(istream& in,Student &s1);
friend ostream& operator <<(ostream& out,Student &s1);
bool pass();
double puttotal();
static int putstun();
static double puttotn();
private:
string name;
double cpp;
double math;
double english;
double total;
static int stu_num; //学生人数,处理为类的静态成员合适
static double total_sum; //学生总分和
};
int Student::stu_num = 0;
double Student::total_sum = 0;
double Student::puttotal()
{
return total;
}
int Student::putstun()
{
return stu_num;
}
double Student::puttotn()
{
return total_sum;
}
istream& operator >>(istream& in,Student &s1)
{
in>>s1.name>>s1.cpp>>s1.math>>s1.english;
s1.total=s1.cpp+s1.math+s1.english;
Student::total_sum+=s1.total;
Student::stu_num++;
return in;
}
ostream& operator <<(ostream& out,Student &s1)
{
out<<s1.name<<'\t';
out<<s1.cpp<<'\t'<<s1.math<<'\t'<<s1.english<<'\t'<<s1.total<<'\t';
return out;
}
bool Student::pass()
{
if(cpp>=60&&math>=60&&english>=60)
return true;
else
return false;
}
int main( )
{
Student stud[200]; //stud[200]为保存数据的对象数组
double aver;
int i=0;
ifstream inflie("score.dat",ios::in);
if(!inflie)
{
cerr<<"open error!"<<endl;
exit(1);
}
while(!inflie.eof())
{
inflie>>stud[i];
++i;
}
inflie.close();
if(Student::putstun()>0)
{
aver=Student::puttotn()/Student::putstun();
ofstream outflie("pass_score.dat",ios::out);
if(!outflie)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(int j=0; j<Student::putstun(); ++j)
{
if(stud[j].puttotal()>aver&&stud[j].pass())
{
outflie<<stud[j]<<endl;
}
}
outflie.close();
cout<<"筛选完成!"<<endl;
}
//总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中
return 0;
}
图片:
心得:
错的惨不忍睹啊。。。
先是在Student::putstun()(输出学生人数)那老是提示说不能没有对象,然后我才发现是在类中声明时忘了加上static。。。
还有个目前也不太明白的,运行时报错
百度了一下这个,大意是使用了空指针。尼玛想了N久才找找原来是定义类时我顺手把参数初始化列表弄上了。。。可为什么不行呢。。。
Student(string na='\0',double cp=0,double ma=0,double eng=0,double tot=0):name(na),cpp(cp),math(ma),english(eng),total(tot) {}