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

烂漫一生 提交于 2020-01-19 05:37:27

问题


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.

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

回答1:


These both inherit from ostream so try this:

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

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




回答2:


Yes. Let your function be

sayhello(std::ostream &os);

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

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



来源:https://stackoverflow.com/questions/10356300/is-it-possible-to-pass-cout-or-fout-to-a-function

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