建立一个对象数组,内放10个学生的数据(姓名、学号、成绩),建立一个函数max,用指向对象的指针做函数参数,在max函数中找出10个学生中成绩最高者,并输出其学号。根据学号,将对象的姓名、成绩等信息使用拷贝构造函数,拷贝到一个新对象中。对对象进行打印输出,并编写程序调试。
时间: 2023-05-25 12:04:06 浏览: 40
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int id;
int grade;
Student(string name, int id, int grade) {
this->name = name;
this->id = id;
this->grade = grade;
}
Student(const Student& other) {
this->name = other.name;
this->id = other.id;
this->grade = other.grade;
}
void print() const {
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
cout << "Grade: " << grade << endl;
}
};
void max(Student* students, int n) {
int maxIndex = 0;
for (int i = 1; i < n; i++) {
if (students[i].grade > students[maxIndex].grade) {
maxIndex = i;
}
}
cout << "Student with highest grade (ID): " << students[maxIndex].id << endl;
// Copy student with highest grade to new object
Student topStudent = students[maxIndex];
cout << "\nCopied student:\n";
topStudent.print();
}
int main() {
Student students[10] = {
Student("Alice", 1, 95),
Student("Bob", 2, 80),
Student("Charlie", 3, 87),
Student("David", 4, 92),
Student("Emily", 5, 78),
Student("Frank", 6, 89),
Student("Gina", 7, 83),
Student("Henry", 8, 96),
Student("Iris", 9, 91),
Student("Jack", 10, 85)
};
max(students, 10);
return 0;
}