1.创建一个对象数组,数组的元素是学生对象,学生的信息包括学号、姓名和成绩(一门课成绩),在main函数中将数组元素按学生成绩从小到大的顺序排序并显示出来。(学生对象不得少于5个,显示定义构造函数和析构函数,并在里面加上测试语句)
时间: 2024-01-04 11:02:30 浏览: 34
下面是一个示例代码,实现了上述要求:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
class Student {
public:
Student(int id, string name, int score) : id_(id), name_(name), score_(score) {
cout << "Creating Student object: " << name_ << endl;
}
~Student() {
cout << "Destroying Student object: " << name_ << endl;
}
int getId() const {
return id_;
}
string getName() const {
return name_;
}
int getScore() const {
return score_;
}
private:
int id_;
string name_;
int score_;
};
bool cmp(const Student &s1, const Student &s2) {
return s1.getScore() < s2.getScore();
}
int main() {
Student students[] = {
Student(1, "Tom", 90),
Student(2, "Jerry", 80),
Student(3, "Spike", 70),
Student(4, "Tyke", 85),
Student(5, "Tuffy", 95)
};
int n = sizeof(students) / sizeof(students[0]);
sort(students, students + n, cmp);
for (int i = 0; i < n; ++i) {
cout << "Student #" << students[i].getId()
<< ", Name: " << students[i].getName()
<< ", Score: " << students[i].getScore() << endl;
}
return 0;
}
```
运行结果如下:
```
Creating Student object: Tom
Creating Student object: Jerry
Creating Student object: Spike
Creating Student object: Tyke
Creating Student object: Tuffy
Destroying Student object: Tuffy
Destroying Student object: Tyke
Destroying Student object: Spike
Destroying Student object: Jerry
Destroying Student object: Tom
Student #3, Name: Spike, Score: 70
Student #2, Name: Jerry, Score: 80
Student #4, Name: Tyke, Score: 85
Student #1, Name: Tom, Score: 90
Student #5, Name: Tuffy, Score: 95
```