将ostream的引用作为函数参数传递

时间:2016-04-08 23:40:46

标签: c++ ostream

我试图创建一个将ostream对象作为参数的函数,然后打印到它。我计划传递部分fstream(文件)和cout

这是我的代码:

void printTask(int op1, int op2, int len, char operation, std::ostream& os = std::cout)
{
    os << endl << "  " << setw(len) << op1 << endl;
    os << operation << " " << setw(len) << op2 << endl;
    os << "-------------" << endl;
    os << "  ";
    for(int i = 0; i < len; i++)
    {
        os << "?";
    }
    os << endl;
}

来自main(),就像这样......

ofstream output("output.txt", ios::out);
cout << addition(xyz, output) << endl;

并且该功能如下所示:

int addition(int xyz, ofstream file)
{
int op1 = ...;
int op2 = ...;
char choice = ...;

printTask(op1, op2, xyz, choice, file);
printTask(op1, op2, xyz, choice, cout); //this cout is not necessary, default parameter
}

我收到关于std::ios::base是私有的错误,但我确实通过引用传递了我的ostream对象,因此它不会尝试使用复制构造函数。

有什么想法吗?

编辑:想要用答案更新这个。 addition的原型错误,ofstream应该通过引用传递,而不是复制它。 这有效: int addition(int xyz, ofstream& file) {...}

非常感谢@ Jarod42

0 个答案:

没有答案
相关问题