


声明一个Student类,在该类中包括一个数据成员id(学号)score(分数)、两个静态数据成员total score(总分)和count(学生人数);
成员函数包括id、score的获取接口,还包括一个成员函数setScore(用于设置分数、累计学生的成绩之和、累计学生人数),一个静态成员函数 sum()用于返回学生的成绩之和,另一个静态成员函数average()用于求全班成绩的平均值。prinfStudentlInfo()用于输出所录入的学生信息,在main函数中,输入某班同学的成绩,并调用上述函数输出所录入的学生信息,并求出全班学生的成绩之和和平均分。
#include <iostream>
class Student {
private:
int id;
int score;
static int totalScore;
static int count;
public:
Student(int id, int score) : id(id), score(score) {
totalScore += score;
count++;
}
int getId() const {
return id;
}
int getScore() const {
return score;
}
void setScore(int score) {
totalScore = totalScore - this->score + score;
this->score = score;
}
static int sum() {
return totalScore;
}
static double average() {
return (double) totalScore / count;
}
void printStudentInfo() const {
std::cout << "学号: " << id << " 成绩: " << score << std::endl;
}
};
int Student::totalScore = 0;
int Student::count = 0;
int main() {
int n;
std::cout << "学生数: ";
std::cin >> n;
Student* students = new Student[n];
for (int i = 0; i < n; i++) {
int id, score;
std::cout << "输入第 " << i + 1 << " 个的学号和成绩: ";
std::cin >> id >> score;
students[i] = Student(id, score);
}
std::cout << "学生信息: " << std::endl;
for (int i = 0; i < n; i++) {
students[i].printStudentInfo();
}
std::cout << "总分: " << Student::sum() << std::endl;
std::cout << "平均: " << Student::average() << std::endl;
delete[] students;
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:
如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^