建立一个对象数组,内放4个学生的数据(姓名、学号、成绩),输出成绩最高者。用c++的形式
时间: 2024-02-17 15:03:38 浏览: 22
好的,根据您的要求,我来设计一个学生类的C++代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int id;
double score;
Student() {}
Student(string n, int i, double s) {
name = n;
id = i;
score = s;
}
};
int main() {
Student students[4] = {
Student("张三", 101, 89.5),
Student("李四", 102, 92.0),
Student("王五", 103, 87.5),
Student("赵六", 104, 95.0)
};
Student highestScoreStudent = students[0];
for (int i = 1; i < 4; i++) {
if (students[i].score > highestScoreStudent.score) {
highestScoreStudent = students[i];
}
}
cout << "成绩最高者:" << highestScoreStudent.name << ",学号:" << highestScoreStudent.id << ",成绩:" << highestScoreStudent.score << endl;
return 0;
}
```
解释一下代码:
首先定义了一个学生类Student,包括了姓名、学号、成绩这些属性,以及两个构造函数(一个是默认构造函数,一个是带参数的构造函数)。
接着,在main函数中,创建了一个学生对象数组students,包含了四个学生对象,每个对象的数据通过构造函数初始化。
然后,定义了一个highestScoreStudent对象,用于存储成绩最高的学生。通过一个for循环,遍历整个学生数组,找到成绩最高的学生对象,将其赋值给highestScoreStudent对象。
最后输出了结果,完成了程序的设计。