c++ - 如何改进我的类(class)以创建输出文件

标签 c++ io

由于我经常需要这个,我想编写一个处理主要 ofstream 事件的类。

我可以这样使用的东西:

OutputFile out("output.txt");
for (int i = 0; i < 10; ++i)
   out << i << "\n";

为此,我编写了以下类:

class OutputFile {
  std::string filename;
  std::ofstream out;

 public:
  explicit OutputFile(std::string filename) {
    this->filename = filename;
    out.open("output/" + filename);
  }
  ~OutputFile() {
    out.close();
  }
  std::ofstream& operator()() { return out; }
};

这几乎是我想要的,但是我重载了运算符 (),因此在上面的示例中我必须使用

out() << i << "\n";

我应该如何修改我的类以便可以用作

out << i << "\n";

最佳答案

您可以重载operator<<在你的类(class)里。

class OutputFile {
  std::string filename;
  std::ofstream out;

 public:
  explicit OutputFile(const std::string &filename)
    : filename(filename), out("output/" + filename) {}

  template<typename T>
  OutputFile& operator<<(const T &value) {
    out << value;
    return *this;
  }
};

关于c++ - 如何改进我的类(class)以创建输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70415777/

相关文章:

c++ - 我可以在特定部分中放置完整的命名空间吗?

c++ - 在C++11中如何表达普通的存储(导出)和加载(导入)屏障(fence)?

Java 文件 IO 因大量连续写入而变慢

io - NFS挂载共享读/写太慢

java - 使用FileOutputStream写入的数据在重新启动程序后消失

python - 使用Python按行读取文件时出现OSError : [Errno 22] Invalid argument,

c# - 将 C char[][] 数组编码到 C#

c++ - 如何在 C++ 中创建 OpenOffice 文档

c++ - 多属性排序是反转元素

unicode - 我如何使用 io.open 在 lua 中打开 unicode 路径