gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:44:57 25 4
gpt4 key购买 nike

我对 C++ 编程还很陌生,我一直在尝试制作一个学生数据库程序,其中已完成类(class)的分数将按升序排序。这里棘手的部分是我在类中声明的变量必须保持私有(private)。在我的排序函数中使用变量显示错误,指出表达式必须具有类。我真的不知道解决这个问题的方法是什么。任何帮助是极大的赞赏! :)代码是`

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

`

最佳答案

也许你的意思是

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。

关于c++ - 表达式必须有类类型(学生数据库)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24743656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com