读取文本文件的 C++ 类 - 出现错误

标签 c++ class

我有以下代码使用类定义读取文本文件。我创建了 TermGrade.h 文件和 TermGrade.cpp 文件。但我得到的错误很少:

在 TermGrade.h 文件中,我收到警告,它找不到任何已定义函数(Readdata、MidsemesterScore、FinalScore 和 LetterGrade)的定义,即使我在 .cpp 文件中定义了它们。

但是,主要问题是在 TermGrade.cpp 文件中出现错误“错误:重载函数“getline”的实例与参数列表不匹配”,它还提示标识符“inLine”未定义,但它不会在下一个语句中提示 inLine,但该语句表示两者 dataLines[lineNumber] 未定义!我是否需要在 .cpp 文件中定义这些变量?任何帮助将不胜感激。

谢谢, 比尔。

// TermGrade.h file

#ifndef TERMGRADE_H
#define TERMGRADE_H

#include <string>
#include<iostream>
#include<fstream>
using namespace std;

class TermGrade {
public:
    TermGrade(string fileName) {};
    string StudentID;
    int assignments;
    int exam1;
    int exam2;
    int final;
    bool records = true;

private:
    string inLine;
    string dataLines[100];
    int lineNumber = 0;


    bool Readdata(istream& in);         // Read line of data from input file
    double MidsemesterScore() const;    // Calculates average 
    double FinalScore() const;          // Calculates average 
    char LetterGrade() const;           // Determines grade


}; // end class Termgrade

#endif

// TermGrade.cpp file

#include "TermGrade.h" // TermGrade class definition
#include<iostream>
#include<fstream>

TermGrade::TermGrade(string fileName) {
    ifstream infile;
    infile.open(fileName);

}


bool Readdata(istream& infile)
{
    if (!infile.eof)
    {
        getline(infile, inLine);
        dataLines[lineNumber] = inLine;
        return true;
    }
    return false;
}

double MidsemesterScore()
{
    return 0.0;
}

double FinalScore()
{
    return 0.0;
}

char LetterGrade()
{
    return 'a';
}

最佳答案

In the TermGrade.h file I get the warning that it cannot find a definition for any of the defined functions ( Readdata, MidsemesterScore, FinalScore and LetterGrade) even though I have them defined in the .cpp file.

不,您没有在 .cpp 文件中定义它们。例如,您没有 TermGrade::Readdata 方法的定义。该方法未在任何地方定义。您确实在其中有一个名为 Readdata 的函数,但它与 TermGrade::Readdata 方法没有任何关系。

关于您遇到的其他一些错误:

您正在调用一个名为 getline() 的函数,但是您没有在任何地方定义该函数,这就是您收到编译器错误的原因。也许您打算引用 C++ 库中的 std::getline() 函数,如果是这样,那么您应该引用它。

此外,您正在传递对名为 istream 的类的引用,遗憾的是您没有在任何地方定义此类。如果您打算引用 std::istream 类,那么您应该像这样引用它。

但是,std::istream 类没有名为eof 的成员。不过,它确实有一个 eof() 方法。

关于读取文本文件的 C++ 类 - 出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303360/

相关文章:

C++内联运算符重载,引用当前对象

c++ - 如何让Win32 APP背景透明?

c++ - 引用未初始化的内存而不访问它是否合法?

python - 检查变量是否属于python中的类

c++ - 单独文件中的简单类和标题不起作用

php - 如何在PHP中调用父类的非静态方法形成子类的静态方法

android onclicklistener 在类里面有按钮吗?

c++ - 使用 string.size() 时获取无限循环

c++ - 模板对象数组

c++ - 延迟渲染 : Performance issues