#include<iostream> using namespace std;class student {private: int num, math; char name[20];public: void input() { for (int i = 0; i < 5; i++) { cout << "请输入第" << i + 1 << "个学生的名字,学号,成绩" << endl; cin >> stu[i].name >> stu[i].num >> stu[i].math; } } student display() { for (int a = 0; a < 5; a++) { for (int b = a + 1; b < 5; b++) { if (stu[a].math > stu[b].math) { student c; c = stu[a]; stu[a] = stu[b]; stu[b] = c; } } } for (int d = 0; d < 5; d++) { cout << stu[d].name << stu[d].num << stu[d].math << endl; cout << endl; } }};student stu[5];int main(){ student* p; p = stu; p->input(); p = stu; p->display();}代码问题
时间: 2024-03-17 15:44:04 浏览: 48
使用include <iostream>时一定要加using namespace std
这段代码有几个问题:
1. 在类中的成员函数input()中,应该使用类中的变量stu[],而不是全局变量stu[]。需要将input()函数改为:
```
void input() {
for (int i = 0; i < 5; i++) {
cout << "请输入第" << i + 1 << "个学生的名字,学号,成绩" << endl;
cin >> name >> num >> math;
}
}
```
2. 在display()函数中,应该在输出每个学生的信息时,为其添加分隔符。需要将display()函数改为:
```
student display() {
for (int a = 0; a < 5; a++) {
for (int b = a + 1; b < 5; b++) {
if (stu[a].math > stu[b].math) {
student c;
c = stu[a];
stu[a] = stu[b];
stu[b] = c;
}
}
}
for (int d = 0; d < 5; d++) {
cout << stu[d].name << " " << stu[d].num << " " << stu[d].math << endl;
}
}
```
3. 在main()函数中,应该在调用类的成员函数时,使用指针访问。需要将main()函数改为:
```
int main() {
student* p;
p = stu;
p->input();
p = stu;
p->display();
}
```
阅读全文