C++ 是否可以将 cout 或 fout 传递给函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10356300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:56:19  来源:igfitidea点击:

Is it possible to pass cout or fout to a function?

c++fstreamofstream

提问by ChiefTwoPencils

I'm trying to find a way to pass fout or cout to a function. I realize there are logically easy ways to deal with this, like put ifs in any function that outputs data or even just write the function both ways. However, that seems primitive and inefficient. I don't believe this code would ever work, I'm putting it here to ensure it's easy to see what I'd "like" to do. Please be aware that I'm taking a algorithm design class using c++, I'm in no way a seasoned c++ programmer. My class is limited to using the headers you see.

我正在尝试找到一种将 fout 或 cout 传递给函数的方法。我意识到有逻辑上简单的方法来处理这个问题,比如将 ifs 放在任何输出数据的函数中,或者甚至只是以两种方式编写函数。然而,这似乎原始且低效。我不相信这段代码会起作用,我把它放在这里是为了确保很容易看到我“喜欢”做什么。请注意,我正在学习使用 C++ 的算法设计课程,我绝不是经验丰富的 C++ 程序员。我的课程仅限于使用您看到的标题。

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
void helloWorld(char);
ofstream fout;

int main()
{
    fout.open("coutfout.dat");
    helloWorld(c);
    helloWorld(f);

    return 0;
}
void helloWorld(char x)
{
    xout << "Hello World";
    return;
}

回答by Kevin Anderson

These both inherit from ostreamso try this:

这些都继承自ostream所以试试这个:

void sayHello(ostream& stream)
{
    stream << "Hello World";
    return;
}

Then in main, pass in the object (cout or whatever) and it should work fine.

然后在 main 中,传入对象(cout 或其他),它应该可以正常工作。

回答by thb

Yes. Let your function be

是的。让你的功能成为

sayhello(std::ostream &os);

Then, in the function, you can use osin place of xout.

然后,在函数中,您可以使用os代替xout

(By the way, using namespace stddumps the entire std namespace and is not recommended. A using std::coutand the like is all right, though.)

(顺便说一句,using namespace std转储整个 std 命名空间,不推荐。不过,Ausing std::cout之类的都可以。)