派生 std::ofstream 和重载运算符<<



如何从 std::ofstream 类派生,在写入文件之前添加一些操作? 换句话说,替换代码,如

int main()
{
std::ofstream file("file.txt");
file << "something" << std::endl;
return 0;
}

class MyFile : public std::ofstream
{
MyFile(std::string filename) : std::ofstream(filename) {}
??? operator<< ???   <-- HERE1
{
// 1. do some stuff with the input
// 2. if wanted,
// flush it to the base class operator<<
}
};
class MyFileC
{
private:
std::ofstream intern_os;
public:
MyFileC(std::string filename) : intern_os(filename) {}
MyFileC& operator<<( input ???   <-- HERE2  )
{

// 1. do some stuff with the input
// e.g (a) IF the input is a std::string,
// THEN, if it contains "signal",
// OnSignal();
// or (b) if file size is too big, clear it ...
// 2. Flush it (for all possible types):
intern_os << input;
}
};
int main()
{
MyFile file("file2.txt"); // (or with MyFileC)
file << "something" << std::endl;
return 0;
}

例如,我们可以在编写等之前即时过滤。

???行中放什么来享受所有现有的std::ofstream.operator<<((,以及我们的个人补充,请问?

  • HERE1:更优雅,具有继承方式; 或者如果不可能(在下面的评论之后(,
  • HERE2:给什么类型来传递"任何可以传递给内部 std::ofstream"(字符串、整数等(
operator<<

不打算被派生的流类覆盖。相反,您应该覆盖std::basic_streambuf::overflow和/或std::basic_streambuf::xsputn

特别是每当缓冲区溢出时,都会在内部调用overflow。如果要提供自己的缓冲,可以通过重写的流类中的std::basic_streambuf::setp初始化流指针来实现此目的。这些链接附带了如何执行此操作的示例。

这里只有一个表面问题:这些都是缓冲方法。您希望覆盖std::fstream,这是一个类,而不是缓冲区类。因此,您需要做的是双重的:

  1. 如上所述覆盖std::basic_filebuf
  2. 使用std::fstream::rdbuf将文件流对象的关联缓冲区设置为重写的文件缓冲区类的实例。可以在现有std::fstream的实例或该类型的自定义子类上执行此操作。

最新更新