首页 > 解决方案 > 使用ostream& vs cout的优势

问题描述

我听说这ostream&cout输出某些东西(字符串等)时更好用。这是为什么?我可能是错的,但不是比简单的语句ostream更容易操作和使用吗?cout

标签: c++

解决方案


让我们看一个将ostream引用传递给函数的示例:

void My_Function(std::ostream& error_stream)
{
     error_stream << "Error in My_Function";
}

通过使用std::ostream&,我可以将其他流传递给函数:文件流、字符串流、std::cout等等。我还可以从中创建(派生)一个自定义Loggingstd::ostream并将日志流传递给该函数。

如果函数只输出到std::cout,我就失去了使用日志流的能力,或者将文本写入文件(作为记录)。相反,文本将始终转到std::cout。当您想记录基于 GUI 的应用程序的问题时,这是非常令人头疼的事情(因为 GUI 应用程序没有用于输出的控制台窗口)。输出到文件会记录刚刚滚动的输出与控制台输出。

想想通用编程,以及与其他模块“即插即用”的能力。Usingstd::ostream&允许函数输出到从 派生的任何东西std::ostream,包括尚未设计的输出流!

示例用法

以下是一些示例用法:

struct usb_ostream : public std::ostream
{
  // Writes to the USB port
  //...
};

int main()
{
  usb_ostream USB_Output;
  My_Function(USB_Output); // Writes text to USB port

  My_Function(std::cerr);  // Writes to the standard error stream.

  std::ofstream my_file("errors.txt");
  My_Function(my_file);    // Saves error text to a file.

  // Of course:
  My_Function(std::cout);  // Write the text to the console.

  // Maybe we want to parse the output.  
  std::ostringstream error_stream;
  My_Function(error_stream);
  const std::string error_text = error_stream.str();
  // Parse the string ...

  return 0;
}

请注意,在main()函数中,只有一个版本的My_Function()被调用。无需更改即可My_Function()输出My_Function()到各种设备、字符串或输出通道。


推荐阅读