c++编写程序,设计一个学生类student,包括姓名和 3 门课成绩,利用重载运算符“+”将所有学生的成绩相加并放在一个对象中,再对该对象求各门课程的平均分
作者:野牛程序员:2024-10-29 17:03:18 C++阅读 2466
c++编写程序,设计一个学生类student,包括姓名和 3 门课成绩,利用重载运算符“+”将所有学生的成绩相加并放在一个对象中,再对该对象求各门课程的平均分
c++编写程序,设计一个学生类student,包括姓名和 3 门课成绩,利用重载运算符“+”将所有学生的成绩相加并放在一个对象中,再对该对象求各门课程的平均分
以下是一个 C++ 程序,设计了一个 Student 类,包括姓名和三门课程的成绩。通过重载运算符 + 来将多个学生的成绩相加,并计算各门课程的平均分:
#include <iostream>
#include <string>
#include <vector>
class Student {
private:
std::string name;
int scores[3]; // 三门课的成绩
public:
// 构造函数
Student(const std::string& name, int score1, int score2, int score3)
: name(name) {
scores[0] = score1;
scores[1] = score2;
scores[2] = score3;
}
// 重载 + 运算符
Student operator+(const Student& other) {
Student result("Total", 0, 0, 0);
for (int i = 0; i < 3; ++i) {
result.scores[i] = this->scores[i] + other.scores[i];
}
return result;
}
// 计算平均分
void printAverage(int studentCount) const {
std::cout << "Average Scores: "
<< (static_cast<double>(scores[0]) / studentCount) << ", "
<< (static_cast<double>(scores[1]) / studentCount) << ", "
<< (static_cast<double>(scores[2]) / studentCount) << std::endl;
}
// 打印学生信息
void print() const {
std::cout << "Name: " << name
<< ", Scores: [" << scores[0] << ", " << scores[1] << ", " << scores[2] << "]"
<< std::endl;
}
};
int main() {
std::vector<Student> students;
students.emplace_back("Alice", 85, 90, 78);
students.emplace_back("Bob", 75, 88, 84);
students.emplace_back("Charlie", 92, 85, 90);
Student total("Total", 0, 0, 0);
for (const auto& student : students) {
total = total + student; // 累加成绩
}
total.print(); // 打印总成绩
total.printAverage(students.size()); // 打印平均分
return 0;
}程序说明
Student 类:
包含姓名和三门课程成绩的成员变量。
构造函数初始化姓名和成绩。
重载
+运算符,允许将两个Student对象的成绩相加,返回一个新的Student对象。提供
printAverage方法,用于计算并打印各门课程的平均分。主函数:
创建了一个
Student对象的集合,添加多个学生的信息。通过累加所有学生的成绩,计算总成绩。
最后计算并输出各门课程的平均分。
此程序展示了如何利用运算符重载和对象组合来实现复杂的计算。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

