在同一个对象C++的成员之间传递ifstream变量

Far*_*ide 0 c++ class file object member

目标:使用类变量,以便在对象的成员中声明的ifstream可以由同一对象的以下成员使用,而不必使用函数头参数传递.

问题:创建的对象测试的本地ifstream未在该对象的第二个成员中重用.我必须设置错误,我该如何解决这个问题?

类和文件现在感觉就像爬山一样,但我甚至找不到第一个立足点 - 让爆炸变量起作用!我在网上看了太久但是所有的例子都很复杂,我只是希望有一些基本的工作来开始修修补补.我确定这是一件非常容易让我感到愚蠢的事,非常令人沮丧>:[

main.cpp中

#include "file.h
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    file test;
    test.file_pass();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

file.h

#ifndef FILE_H
#define FILE_H
#include <fstream>
#include <iostream>

using namespace std;

class file
{
    public:

        file();
        void file_pass();

    //private:
        ifstream stream;
};

#endif
Run Code Online (Sandbox Code Playgroud)

file.cpp

#include "file.h"

//**********************************
//This will read the file.
file::file()
{
    ifstream stream("Word Test.txt");
}

//**********************************
//This will output the file.
void file::file_pass()
{
   //ifstream stream("Word Test.txt"); //if line activated, program works fine of course.
    string line;
    while(getline(stream, line))
            cout << line << endl;
}
Run Code Online (Sandbox Code Playgroud)

wim*_*ica 5

在这里,您将创建一个与类成员同名的新局部变量:

file::file()
{
    ifstream stream("Word Test.txt");
}
Run Code Online (Sandbox Code Playgroud)

相反,您可以使用它来初始化构造函数中的类成员:

file::file() : stream("Word Test.txt")
{
}
Run Code Online (Sandbox Code Playgroud)