类中的流语法

fstream syntax in a class

本文关键字:语法      更新时间:2023-10-16

这是我的学生班。该函数static int readRecord(fstream &, Student s[]);

#ifndef STUDENT_H
#define STUDENT_H
#include <fstream>
class Student
{
public:
Student();
Student(char* n, int g[]);
char* getName();
void setName(char* n);
void setGrade(int g[]);
double getGradesAverage(); 
static int readRecord(fstream &, Student s[]); 
static void display(Student s[], int  students);
static void sort(Student s[], int students);
private:
char name[30];
int grades[5];
};

#endif

在我的 cpp 中,我有这个:

int Student::readRecord(fstream & in, Student s[])
{
int j = 0;
if (!in)
{
    cout << "cannot open the file or file does not existsn";
    exit(0);
}
else
{
    char name[30];
    int g[5];
    char ch;
    while (in)
    {
        in >> name;
        for (int i = 0; i<5; i++)
        {
            in >> g[i];
            if (i != 4)
                in >> ch; 
        }
        s[j].setName(name);
        s[j].setGrade(g);
        j++;
    }
}
return j - 1;
}

我收到此编译器错误:

错误

C2061:语法错误:标识符"fstream"

错误 C2511: 'int 学生::读取记录(标准::fstream &,学生 [])" : 在"学生"中找不到重载成员函数

#ifndef STUDENT_H
#define STUDENT_H
#include <fstream>
class Student
{
public:
  Student();
  Student(char* n, int g[]);
  char* getName();
  void setName(char* n);
  void setGrade(int g[]);
  double getGradesAverage(); 
  static int readRecord(std::fstream &file, Student s[]); 
  static void display(Student s[], int  students);
  static void sort(Student s[], int students);
private:
  char name[30];
  int grades[5];
};

如果您不使用using namespace std,则必须使用std::fstream

更好的选择是做using std::fstream而不是using namespace std

我看到的另一个问题是你忘了为fstream对象声明一个名称。

static int readRecord(std::fstream &file, Student s[]); 
//                    ^^^          ^^^^^

另外,由于您使用的是C++因此您不应该再将 char 数组用于字符串,而应该std::string .

我通常会用std::vector替换所有数组的东西。