How do I change a C++ output stream to refer to cout?

眉间皱痕 提交于 2020-02-04 11:41:29

问题


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?


回答1:


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



回答2:


Why does the stream need to be a member?

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


来源:https://stackoverflow.com/questions/7129037/how-do-i-change-a-c-output-stream-to-refer-to-cout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!