标签:
文件score.dat中保存的是若干名学生的姓名和C++课、高数和英语成绩。(1)定义学生类,其中包含姓名、C++课、高数和英语成绩及总分数据成员。
//定义学生类 class Student{ public: //声明必要的成员函数 private: string name; double cpp; double math; double english; double total; static int stu_num; //学生人数,处理为类的静态成员合适 static double total_sum; //学生总分和 };
#include <iostream> #include <cstdlib> #include <fstream> using namespace std; //定义学生类 class Student { public: Student() {}; void input(); void display(); double get_total() { return total; } static int get_stu_num() { return stu_num; } static double get_total_sum() { return total_sum; } bool pass(); private: string name; double cpp; double math; double english; double total; static int stu_num; //学生人数,处理为类的静态成员合适 static double total_sum; //学生总分和 friend istream& operator>>(istream &in, Student &s); friend ostream& operator<<(ostream &out, Student &s); }; int Student::stu_num=0; double Student::total_sum=0; bool Student::pass() { if (cpp>=60 && math>=60 && english>=60) return true; else return false; } istream& operator>>(istream &in, Student &s) { in>>s.name>>s.cpp>>s.math>>s.english; s.total=s.cpp+s.math+s.english; Student::stu_num++; Student::total_sum+=s.total; return in; } ostream &operator<<(ostream &out, Student &s) { out<<s.name<<"\t"; out<<s.cpp<<"\t"; out<<s.math<<"\t"; out<<s.english<<"\t"; out<<s.total; return out; } int main() { Student stu[200]; int num=0,i; double total_avg; ifstream infile("score.dat",ios::in); if(!infile) { cerr<<"error!"<<endl; exit(1); } while (!infile.eof()) { infile>>stu[num++]; } infile.close(); total_avg = Student::get_total_sum() / Student::get_stu_num(); ofstream outfile("pass_score.dat",ios::out); if(!outfile) { cerr<<"error!"<<endl; exit(1); } for(i=0; i<Student::get_stu_num(); i++) { if (stu[i].get_total()>total_avg) { if (stu[i].pass()) { outfile<<stu[i]<<endl; } } } }
@ Mayuko
标签:
原文地址:http://blog.csdn.net/mayuko2012/article/details/46537945