我对编程C++相当陌生,我一直试图制作一个学生数据库程序,其中完成的课程标记将按升序排序。 这里棘手的部分是,我在课堂上声明的变量必须保持私密。在我的排序函数中使用变量显示一个错误,表达式必须有类。我不知道这有什么解决方案。任何帮助是极大的赞赏! :) 代码是'表达式必须具有类类型(学生数据库)?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Student{
private:
int data[100];
string name;
string id;
float cgpa, hcgpa, lcgpa;
int marks[100];
int cc; //courses Completed
public:
int getMarks(void){
int i = 100;
int m;
return m = marks[i];
}
void getInfo(int i){
cout << "Student " << i << ": " << endl;
cout << "ID: ";
cin >> id;
cin.ignore();
cout << "Name: ";
getline(cin, name);
cin.ignore();
cout << "CGPA: ";
cin >> cgpa;
cout << "Number of courses completed: ";
cin >> cc;
cout << "Please enter the marks respectively: " << endl;
for (int j = 1; j <= cc; j++){
cout << "Mark " << j << ": " << endl;
cin >> marks[j];
}
cout << endl;
}
void sortMarks(Student z[], int i, int &n){
int j;
for (i = 0; i < n-1; i++){
j = i;
while (j>0 && z[j - 1].getMarks > z[j].getMarks){
swap(z.[j - 1]getMarks(), z.[j]getMarks());
j--;
}
}
}
void showInfo(int i){
cout << "Student " << i << ": " << endl;
cout << "ID: " << id << endl;
cout << "Name: " << name << endl;
cout << "CGPA: " << cgpa << endl;
cout << "Number of courses completed: " << cc << endl;
cout << endl;
for (int j = 1; j <= cc; j++){
cout << "Marks for course " << j << ": " << endl;
cout << marks[j] << endl;
}
}
};
int main(){
Student s[100];
int no; //should be less than 100
cout << "Number of students: ";
cin >> no;
cout << endl;
for (int i = 1; i <= no; i++) {
s[i].getInfo(i);
}
for (int i = 1; i <= no; i++) {
s[i].showInfo(i);
}
cout << "After sort: \n" << endl;
for (int i = 1; i <= no; i++) {
s[i].sortMarks(i);
s[i].showInfo(i);
}
system("pause");
//Error is it doesn't show the exact values after the first student's info.
}
`
除了Vlad的观点(这可能是问题),你也可以使'sortMarks'静态 - 它不需要有一个学生记录工作。它也看起来像你用错误的论点进一步调用它。最后,我建议你想对一个'Student *'s而不是'Student'的数组进行排序,以避免为每个交换做太多工作,但它仍然可以像这里一样工作。而且你的int&n不需要是一个引用(AFAICS),尽管我看不到sortMarks的正确调用,但我想'i
Rup
@Rup,我明白了,我会解决上述的争论。我使用的引用是为int no变量,但我想你是对的,这不是必需的。我会试试看,并让你知道它是怎么回事:)。非常感谢! – user3838106