由于我经常需要这个,我想编写一个处理主要流活动的类。
我可以这样使用的东西:
OutputFile out("output.txt");
for (int i = 0; i < 10; ++i)
out << i << "\n";
Run Code Online (Sandbox Code Playgroud)
为此,我编写了以下类:
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; }
};
Run Code Online (Sandbox Code Playgroud)
这几乎是我想要的,但是我正在重载运算符(),因此在上面的示例中我必须使用
out() << i << "\n";
Run Code Online (Sandbox Code Playgroud)
我应该如何修改我的类以便我可以用作
out << i << "\n";
Run Code Online (Sandbox Code Playgroud)
operator<<你的班级可能超载。
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;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38 次 |
| 最近记录: |