【问题标题】:c++ using function of type void or std::ostream & to do prints?c++ 使用 void 或 std::ostream & 类型的函数进行打印?
【发布时间】:2016-02-22 23:33:55
【问题描述】:

我想知道使用std::ostream & 返回类型定义函数的原因和优势是什么,而不仅仅是用于打印值的 void 函数。例如,如果我想打印一个字符串文字,我可以通过以下两种方式进行:

std::ostream& print1(std::ostream &os){
     os << "print this message";
     return os;
}
print1(std::cout);

void print2(){
     std::cout << "print this message";
}
print2();

现在使用print1 之类的函数与print2 相比有什么优势?一种比另一种更有效吗?还有其他重要的区别吗?

【问题讨论】:

  • 你可以做ofstream out("somefile.txt"); print1(out);
  • 但是你的问题似乎不是关于返回类型,而是关于是否将它作为参数传递
  • 另外,我假设std::ostream os 应该是std::ostream &amp;os
  • 是的,当然很抱歉,我会马上改正的
  • @MaraJade “效率会有什么不同吗?” 让流的实现担心这一点,直到您可以通过测量证明某些东西效率太低。

标签: c++ printing void ostream


【解决方案1】:

第一种形式的优点是您可以例如组合多个输出函数:

print1(mystream)<<" and that's all !";  

更实际地,您可以轻松地使用文件输出而不是控制台输出,甚至是字符串输出。您还可以编写循环/条件来检查一切是否正常,就像使用标准输出函数一样。是的,因为当您写入文件时,可能会出错(例如磁盘已满):

if (! print1(mystream))
    cout <<" dik full !?"; 

但这只是一种常见的做法。你当然也可以选择第二种形式:

print2();  // yes, put on what stream, always cout ??
if (! cout) 
    cout <<" oops, unexpected output error..."; 

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多