如何更改 C++输出流要引用cout吗?
我有一个类,我想将输出流作为成员提供给该类,即:
class GameBase {
protected:
ofstream m_OutputWriter;
...
}
该类中有一个方法,它接受字符串参数并打开 m_OutputWriter 以指向该文件,因此数据可以通过以下方式输出到该文件:使用标准<<操作员;
但是,我想要的是让流默认指向 cout,这样如果未指定输出路径,输出将转到控制台输出而不是文件,并且调用类将完全透明,谁将使用
m_OutputWriter << data << endl;
将数据输出到预定目的地。然而,我在这里尝试了其他几个例子,但它们似乎都不完全适合我想要做的事情。
我在这里缺少什么?
I have a class that I want to give an output stream as a member to, to wit:
class GameBase {
protected:
ofstream m_OutputWriter;
...
}
There is a method in this class that takes a string argument and opens m_OutputWriter to point to that file, so data may be output to that file by using the standard << operator;
However, what I would like is to make the stream point to cout by default, so that if the output path is not specified, output goes to the console output instead of to a file, and it will be completely transparent by the calling class, who would use
m_OutputWriter << data << endl;
to output the data to the predetermined destination. Yet, I have tried a couple of the other examples here, and none of them exactly seem to fit what I'm trying to do.
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么流需要成为成员?
Why does the stream need to be a member?
除了使用
std::ofstream
作为成员之外,我还会使用返回std::ostream&
的函数。例如:
一个功能齐全的示例:
In addition to having an
std::ofstream
as a member, I would use a function that returns anstd::ostream&
.For example:
A fully-functioning example: