gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:50:06 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com