如何更改C ++输出流以引用cout? [英] How do I change a C++ output stream to refer to cout?
问题描述
我有一个班级,希望将其作为成员提供输出流,例如:
I have a class that I want to give an output stream as a member to, to wit:
class GameBase {
protected:
ofstream m_OutputWriter;
...
}
该类中有一个方法需要字符串参数,然后打开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;
但是,我希望默认情况下使流指向cout,这样,如果未指定输出路径,则输出将进入控制台输出
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.
我在这里缺少什么?
推荐答案
除了拥有 std :: ofstream
作为成员之外,我将使用一个返回 std :: ostream&
的函数。
In addition to having an std::ofstream
as a member, I would use a function that returns an std::ostream&
.
例如:
class GameBase {
std::ofstream m_OutputWriter;
protected:
std::ostream& getOutputWriter() {
if (m_OutputWriter)
return m_OutputWriter;
else
return std::cout;
}
...
}
功能齐全示例:
#include <iostream>
#include <ostream>
std::ostream& get() {
return std::cout;
}
int main() {
get() << "Hello world!\n";
}
这篇关于如何更改C ++输出流以引用cout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!