由于我经常需要这个,我想编写一个处理主要 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/