表达式必须具有类类型(学生数据库)?

时间:2014-07-14 18:50:29

标签: c++

我是编程C ++的新手,而且我一直试图制作一个学生数据库的程序,其中完成的课程标记将按升序排序。 这里棘手的部分是我在类中声明的变量必须保持私有。在我的sort函数中使用变量会显示一个错误,表达式必须具有类。我真的不知道解决方案是什么。任何帮助是极大的赞赏! :) 代码是`

#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.
}

`

1 个答案:

答案 0 :(得分:2)

也许你的意思

swap(z[j - 1].getMarks(), z[j].getMarks());

而不是

swap(z.[j - 1]getMarks(), z.[j]getMarks());

虽然在这种结构中没有任何意义,因为编译器在任何情况下都会发出错误,因为你试图交换getMarks返回的临时对象。

此会员功能

int getMarks(void){
    int i = 100;
    int m; 
    return m = marks[i];

}

根本无效,没有任何意义。

因此您的代码问题不在错误中。问题是你的代码整体无效。

例如,函数sortMarks应定义为静态成员函数。您可以直接访问此函数中的数组标记元素,而无需使用getMarks。