使用ostream&vs cout的优势

  • 本文关键字:cout vs ostream 使用 c++
  • 更新时间 :
  • 英文 :


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

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

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

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

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

想想泛型编程,以及"即插即用"的能力;与其他模块。使用std::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()输出到各种设备,字符串或输出通道。

最新更新