class Student{ public: void setVal();//输入学生信息 float getScore(){return m_score;}//获取成绩 void show();//输出学生信息 private: int m_id{}; //编号 int m_score{}; //成绩 }; 请完成未定义的成员函数,另定义如下普通函数: void input(Student*p, int n); //输入n个学生信息 void scoreSort(Student*p, int n); //对n个学生排序 void print(Student*p, int n); //输出n个学生信息 其中在主函数中输入n并定义学生对象数组。 Input 第一行,一个整数n,表示学生人数,以下n行,每行为一位学生的信息。 用C++写出其代码
时间: 2023-12-03 19:46:36 浏览: 116
以下是代码实现:
```c++
#include<iostream>
#include<algorithm>
using namespace std;
class Student{
public:
void setVal(); //输入学生信息
float getScore(){return m_score;} //获取成绩
void show(); //输出学生信息
private:
int m_id{}; //编号
int m_score{}; //成绩
};
void Student::setVal(){
cin >> m_id >> m_score;
}
void Student::show(){
cout << m_id << " " << m_score << endl;
}
void input(Student *p, int n){
for(int i=0;i<n;i++){
p[i].setVal();
}
}
bool cmp(Student a, Student b){
return a.getScore()>b.getScore();
}
void scoreSort(Student *p, int n){
sort(p,p+n,cmp);
}
void print(Student *p, int n){
for(int i=0;i<n;i++){
p[i].show();
}
}
int main(){
int n;
cin >> n;
Student *students=new Student[n];
input(students,n);
scoreSort(students,n);
print(students,n);
delete[] students;
return 0;
}
```
其中,我们首先定义了一个 `Student` 类,包含了三个成员函数:`setVal()`、`getScore()` 和 `show()`,分别用于输入学生信息、获取成绩和输出学生信息。同时,类中还包含了两个私有成员变量:`m_id` 表示编号,`m_score` 表示成绩。
接下来,我们定义了三个普通函数:`input()`、`scoreSort()` 和 `print()`,分别用于输入学生信息、对学生排序和输出学生信息。其中,`input()` 函数接受一个 `Student` 类型的指针 `p` 和一个整数 `n`,表示输入 n 个学生信息。`scoreSort()` 函数接受一个 `Student` 类型的指针 `p` 和一个整数 `n`,表示对 n 个学生按照成绩从高到低排序。`print()` 函数接受一个 `Student` 类型的指针 `p` 和一个整数 `n`,表示输出 n 个学生的信息。
最后,在主函数中,我们首先输入学生人数 `n`,然后定义一个 `Student` 类型的指针数组 `students`,长度为 `n`。接着,调用 `input()` 函数输入学生信息,再调用 `scoreSort()` 函数对学生按成绩排序,最后调用 `print()` 函数输出学生信息。需要注意的是,程序结束前要记得释放内存,即调用 `delete[] students`。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)