题目
【问题描述】
1.定义一个学生类,包含姓名、年龄、绩点,要求能够初始化学生信息(定义常规构造函数和拷贝构造函数)、显示学生信息、设置学生信息;
2.在主函数中定义一个学生数组(普通数组或者动态数组都可以),大小为5,然后利用设置学生信息的成员函数输入每个学生信息;
3.定义student类的友元函数Sort实现按绩点排序,以对象指针(或对象数组)和数组大小为参数,对学生按绩点由高到低排序。在主函数中调用函数sort,输出排序后的学生信息。
【代码】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include<iostream> #include<string> #include<algorithm>
using namespace std;
class Student { private: string name; int age; double gpa; public: Student() {} Student(const string& n, int a, double g) : name(n), age(a), gpa(g) {} Student(const Student& s) : name(s.name), age(s.age), gpa(s.gpa) {}
void display() const { cout << "Name: " << name << endl; cout << "Age: " << age << endl; cout << "GPA: " << gpa << endl; }
void set(const string& n, int a, double g) { name = n; age = a; gpa = g; }
friend void Sort(Student* arr, int size); };
void Sort(Student* arr, int size) { sort(arr, arr + size, [](const Student& a, const Student& b) { return a.gpa > b.gpa; }); }
int main() { Student arr[5]; for (int i = 0; i < 5; i++) { string name; int age; double gpa; cout << "Enter information for student " << i+1 << endl; cout << "Name: "; getline(cin, name); cout << "Age: "; cin >> age; cout << "GPA: "; cin >> gpa; cin.ignore(); arr[i].set(name, age, gpa); }
Sort(arr, 5);
cout << "Sorted student information: " << endl; for (int i = 0; i < 5; i++) { arr[i].display(); } return 0; }
|
代码可能略有不足,请大佬多多指教