Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;将文件连接返回到成员,以便同一类的其他方法可以使用_C++_File_Oop_File Io_Singleton - Fatal编程技术网

C++ c++;将文件连接返回到成员,以便同一类的其他方法可以使用

C++ c++;将文件连接返回到成员,以便同一类的其他方法可以使用,c++,file,oop,file-io,singleton,C++,File,Oop,File Io,Singleton,我来自PHP。在PHP中,我们可以将文件处理程序返回到变量: class FileHandler { private $_fileHandler; public function __construct() { $this->_fileHandler = fopen('log.txt', 'a'); } public function writeToFile($sentence)

我来自PHP。在PHP中,我们可以将文件处理程序返回到变量:

    class FileHandler
    {
      private $_fileHandler;

      public function __construct()
       {
              $this->_fileHandler = fopen('log.txt', 'a');
       }

      public function writeToFile($sentence)
       {
               fwrite($this->_fileHandler, $sentence);
       }
     }
我面临的问题是,C++中,当我想把它分配给一个成员时,它会出错,这样我就可以通过我的类

使用它。
  FileUtils::FileUtils()
  {
    // I do not what type of variable to create to assign it
    string handler = std::ofstream out("readme.txt",std::ios::app); //throws error. 
    // I need it to be returned to member so I do not have to open the file in every other method
  }

只需使用可以通过引用传递的filestream对象:

void handle_file(std::fstream &filestream, const std::string& filename) {
    filestream.open(filename.c_str(), std::ios::in);//you can change the mode depending on what you want to do
    //do other things to the file - i.e. input/output
    //...
}
用法(在int main或类似版本中):

通过这种方式,您可以传递原始的
filestream
对象,以便对该文件执行任何操作。还要注意的是,如果只想使用输入文件流,可以将函数专门化为
std::ifstream
,反之,可以使用
std::ofstream
输出文件流

参考资料:

std::fstream filestream;
std::string filename;

handle_file(filestream, filename);