为什么在使用void函数时出现错误代码C2276?

时间:2020-07-09 18:20:51

标签: c++ compiler-errors

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

class Movie
{
private:
    ifstream inMovie;       //private member variables

    void openFile();
    void testFile();
    void readFile();

public:
    Movie();                //constructor
    void driver()
    {
        openFile();

    };          
};

void Movie::openFile()
{
    ifstream inMovie;
    inMovie.open("SciFiMovies.txt");
    testFile();
    readFile();
}

void Movie::testFile()
{
    ifstream inMovie;
    if (!inMovie.open)
    {
        cout << "Unable to open the file.";
        exit(1);
    }
}

void Movie::readFile()
{
    ifstream inMovie;
    string file;
        while (!inMovie.eof)
        {
            getline(inMovie, file);
            cout << file;
        }
}

int main()
{
    Movie movObj;
    movObj.driver();
    system("pause");
    return 0;
}

为什么我收到错误代码?使用 !当我要测试文件是否无法打开或读取文件时,通常对我有用。另外,老师要求我们使用几个不同的void函数,这就是为什么程序看起来有点奇怪的原因(使用多个函数来完成一个简单的任务)。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:3)

您有:

if (!inMovie.open)

while (!inMovie.eof)

openeof都是函数,而不是数据成员。您需要在它们上包含(),如下所示:

if (!inMovie.open())

while (!inMovie.eof())

另外,建议阅读以下内容:Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?

同样,与错误无关,但是由于您在每个函数中重新定义了inMovie,因此最终所有这两个检查都是false。删除重新定义,并依靠类成员变量。