开发者

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;
...
}

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?


Why does the stream need to be a member?

struct GameBase {
    void out(std::ostream& out = std::cout);
    // ...
};


In addition to having an std::ofstream as a member, I would use a function that returns an std::ostream&.

For example:

class GameBase {
    std::ofstream m_OutputWriter;
protected:
    std::ostream& getOutputWriter() {
         if (m_OutputWriter)
             return m_OutputWriter;
         else
             return std::cout;
    }
    ...
}

A fully-functioning example:

#include <iostream>
#include <ostream>

std::ostream& get() {
    return std::cout;
}

int main() {
    get() << "Hello world!\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜