是否可能传递cout或fout到一个函数? [英] Is it possible to pass cout or fout to a function?

查看:204
本文介绍了是否可能传递cout或fout到一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个方法来传递fout或cout到一个函数。我意识到有逻辑上很容易的方法来处理这个,就像在任何函数输出数据,或者甚至只是写两个方法的函数。然而,这似乎原始和低效。我不相信这个代码会工作,我把它放在这里,以确保很容易看到我会喜欢做什么。请注意,我正在使用c ++的算法设计类,我不是一个经验丰富的c ++程序员。我的类仅限于使用您看到的标头。

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


推荐答案

c $ c> ostream 所以试试这个:

These both inherit from ostream so try this:

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

然后在main中传入对象工作正常。

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

这篇关于是否可能传递cout或fout到一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆