文件流对象最好随时使用随时创建,不要成为类成员

来源:互联网 发布:java const 关键字 编辑:程序博客网 时间:2024/06/02 09:36

类最好不要拥有fstream 成员:

      因为文件对象的打开关闭等操作随运行时的各种环境变化而易出现不容易觉察的操作失败。

此时为测试带来了困难。

 

      所以文件流对象最好随用随取。

例如如下一个对象的函数成员的函数体就比较可取,其中fstream对象outFile不是类的成员

 fstream outFile;
 outFile.open(fName, ios::binary  | ios::app );
 if(outFile.fail())
 {
  cout<<"can't open file !"<<endl;
  return;
 }
 outFile.seekp(0,ios::end);
 t.writeToFile(outFile);
 outFile.close();

原创粉丝点击