Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/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++ 如何重用包含std::ifstream的类?_C++ - Fatal编程技术网

C++ 如何重用包含std::ifstream的类?

C++ 如何重用包含std::ifstream的类?,c++,C++,我有一个通过打开、读取和关闭来处理文件的类a。我还有另一个B类,它使用A来读取文件。B将A的实例作为私有成员数据。我想重用a,并使用该实例读取多个文件。我还读了一些我们不能复制任何流的地方。所以我的问题是如何处理类A来读取B中的多个文件 class A{ A(std::string s){ f.open(s); } void read_file(){ /// read file // close after reading

我有一个通过打开、读取和关闭来处理文件的类a。我还有另一个B类,它使用A来读取文件。B将A的实例作为私有成员数据。我想重用
a
,并使用该实例读取多个文件。我还读了一些我们不能复制任何流的地方。所以我的问题是如何处理类A来读取B中的多个文件

class A{
   A(std::string s){
      f.open(s);
   }
   void read_file(){
        /// read file

        // close after reading
        f.close();
    }
private:
   std::ifstream f;
};

class B{
   B(std::string s_):a(s_){}

   void read_multiple_files(){
       a.read_file();
        // now lets read another file
       a = A("another_file_1.txt");
       a.read_file();
       ////////////////////
        // now lets read another file
       a = A("another_file_2.txt");
       a.read_file();
   }
private:
    A a
};

这可能是一个设计问题。似乎没有理由让
B
保存
A
的实例,除非它需要在不同的方法调用之间保留一个文件句柄

相反,只需创建一个
A
来读取每个文件:

class B {
   void read_multiple_files() {
        // read our files
       auto result = A("another_file_1.txt").read_file();
       auto result_2 = A("another_file_2.txt").read_file();
       ...
   }
}

为什么
B
需要包含
A
的实例?为什么不为需要在
内部打开的每个文件创建一个
A
?在您的示例中,没有任何东西不能用免费函数和本地文件流来完成。这也会给你更多的处理错误的灵活性。你试过你的代码吗?@donkopotamus这是我的想法,但我想确定这是否是一种有效的方法?@vantamula是的,很好。。。你担心什么“效率低下”?