大神,设计一个Student类,类中包含学生基本数据:学号、姓名、性别、数学成绩、英语成绩、计算机成绩。

2025-03-14 08:06:18
推荐回答(1个)
回答1:

#include
#include
#include
#include
#include
using std::string;
using std::cin;
using std::cout;
using std::istream;
using std::ostream;
using std::list;
using std::ofstream;
using std::ios;

class Score{
int cpp;
int math;
int english;
friend istream& operator >> (istream& in, Score& score);
friend ostream& operator << (ostream& out, const Score& score);
};
class Student{
string name;
string sex;
int age;
Score score;
friend istream& operator >> (istream&, Student&);
friend ostream& operator << (ostream& out, const Student& stu);
public:
void setScore(Score score);
};
void Student::setScore(Score score)
{
Student::score = score;
}
istream& operator >> (istream& in, Student& stu)
{
in >> stu.name
>> stu.sex
>> stu.age;
return in;
}
ostream& operator << (ostream& out, const Student& stu)
{
out << stu.name << " "
<< stu.sex << " "
<< stu.age << " "
<< stu.score << " ";
return out;
}
istream& operator >> (istream& in, Score& score)
{
in >> score.cpp
>> score.math
>> score.english;
return in;
}
ostream& operator << (ostream& out, const Score& score)
{
out << score.cpp << " "
<< score.math << " "
<< score.english << std::endl;
return out;
}
void save_student_info(list &stu_list)
{
ofstream file;
file.open("student.dat", ios::out | ios::app);
list::iterator iter;
if(file.is_open()){
for(iter = stu_list.begin(); iter != stu_list.end(); iter++)
{
file << *iter;
}
file.close();
}else{
cout << "can't open file!";
}
}
void type_in_student_info(list &stu_list)
{
char ch;
while(true){
cout << "是否录入(Y/N):";
cin >> ch;
if('N' == ch || 'n' == ch){
break;
}
cout << "请输入学生信息(姓名、性别、年龄):";
Student stu;
cin >> stu;

cout << "请输入学生成绩(c++、数学、英语):";
Score score;
cin >> score;

stu.setScore(score);

stu_list.push_back(stu);
}
save_student_info(stu_list);
}

int main()
{
list stu_list;
//输入学生信息
type_in_student_info(stu_list);

return 0;