定义一个学生类,录入学生信息,保存,登记成绩,c++
时间: 2024-01-22 07:43:15 浏览: 33
以下是一个简单的学生类的定义,包含了学生的姓名、年龄、性别、学号和成绩等信息,并且提供了录入学生信息、保存、登记成绩等功能。具体实现可以根据需求进行修改和完善。
```c++
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
// 学生类
class Student {
public:
// 构造函数
Student(string name, int age, char gender, string id) {
this->name = name;
this->age = age;
this->gender = gender;
this->id = id;
}
// 录入学生信息
static Student inputStudent() {
string name, id;
int age;
char gender;
cout << "请输入学生姓名:";
cin >> name;
cout << "请输入学生年龄:";
cin >> age;
cout << "请输入学生性别(M/F):";
cin >> gender;
cout << "请输入学生学号:";
cin >> id;
return Student(name, age, gender, id);
}
// 保存学生信息
void save(string filename) {
ofstream out(filename, ios::app);
out << name << "," << age << "," << gender << "," << id << endl;
out.close();
}
// 登记成绩
void addScore(double score) {
scores.push_back(score);
}
// 获取平均成绩
double getAverageScore() const {
if (scores.empty()) {
return 0;
}
double sum = 0;
for (auto score : scores) {
sum += score;
}
return sum / scores.size();
}
// 获取学生姓名
string getName() const {
return name;
}
private:
string name; // 姓名
int age; // 年龄
char gender; // 性别
string id; // 学号
vector<double> scores; // 成绩
};
```
使用示例:
```c++
int main() {
Student s = Student::inputStudent();
s.save("students.txt");
s.addScore(90);
s.addScore(85);
s.addScore(95);
cout << s.getName() << "的平均成绩是:" << s.getAverageScore() << endl;
return 0;
}
```