如何更改 C++输出流要引用cout吗?

发布于 2024-11-30 15:56:50 字数 424 浏览 1 评论 0原文

我有一个类,我想将输出流作为成员提供给该类,即:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-12-07 15:56:50

为什么流需要成为成员?

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

Why does the stream need to be a member?

struct GameBase {
    void out(std::ostream& out = std::cout);
    // ...
};
感性不性感 2024-12-07 15:56:50

除了使用 std::ofstream 作为成员之外,我还会使用返回 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";
}

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";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文