在上一题学生类的基础上,设置一个普通函数Max,用指向对象的指针作为函数参数,在Max中找出5个学生中成绩最高者,并输出该学生的信息,在主函数中进行测试。
时间: 2024-03-23 19:44:04 浏览: 9
好的,根据您的要求,我来为您编写代码:
```C++
#include <iostream>
#include <string>
using namespace std;
class Student{
public:
string name;
int score;
Student(string name, int score){
this->name = name;
this->score = score;
}
void display(){
cout << "Name: " << name << ", Score: " << score << endl;
}
};
void Max(Student* stuArr[], int n){
int maxScore = 0;
int index = 0;
for(int i = 0; i < n; i++){
if(stuArr[i]->score > maxScore){
maxScore = stuArr[i]->score;
index = i;
}
}
cout << "Max Score: ";
stuArr[index]->display();
}
int main(){
Student* stuArr[5];
stuArr[0] = new Student("Alice", 80);
stuArr[1] = new Student("Bob", 90);
stuArr[2] = new Student("Charlie", 95);
stuArr[3] = new Student("David", 75);
stuArr[4] = new Student("Eva", 85);
Max(stuArr, 5);
return 0;
}
```
运行结果:
```
Max Score: Name: Charlie, Score: 95
```
这里我们定义了一个普通函数Max,它有两个参数:指向对象的指针数组和数组的长度。在函数中,我们遍历了整个数组,找出了成绩最高的学生,并输出了该学生的信息。最后在主函数中,我们创建了5个学生对象,然后调用了Max函数来测试它的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)