6-2 2020Student类与对象数组 分数 10 本题要求定义一个简单的学生类,数
时间: 2024-02-05 08:13:34 浏览: 25
据包括学生姓名、学号和三门课的成绩。然后定义一个包含多个学生对象的数组,计算每个学生的总分和平均分,并输出结果。
以下是一个可能的实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int id;
int score1, score2, score3;
int getTotalScore() {
return score1 + score2 + score3;
}
double getAverageScore() {
return (double)getTotalScore() / 3.0;
}
};
int main() {
const int numStudents = 3;
Student students[numStudents] = {
{"张三", 1001, 80, 90, 85},
{"李四", 1002, 75, 85, 80},
{"王五", 1003, 90, 95, 92}
};
for (int i = 0; i < numStudents; i++) {
Student &s = students[i];
cout << "姓名:" << s.name << endl;
cout << "学号:" << s.id << endl;
cout << "总成绩:" << s.getTotalScore() << endl;
cout << "平均成绩:" << s.getAverageScore() << endl;
cout << endl;
}
return 0;
}
```
这个程序定义了一个 `Student` 类,包括学生的姓名、学号和三门课的成绩。它还包括两个成员函数 `getTotalScore()` 和 `getAverageScore()`,用于计算总分和平均分。
在 `main()` 函数中,我们定义了一个包含三个学生对象的数组,每个对象都被初始化了。然后,我们遍历这个数组,对于每个学生,输出姓名、学号、总成绩和平均成绩。注意,我们使用了引用来避免在循环中进行对象拷贝。