c++ - 使用ostream& vs cout的优势
问题描述
我听说这ostream&
比cout
输出某些东西(字符串等)时更好用。这是为什么?我可能是错的,但不是比简单的语句ostream
更容易操作和使用吗?cout
解决方案
让我们看一个将ostream
引用传递给函数的示例:
void My_Function(std::ostream& error_stream)
{
error_stream << "Error in My_Function";
}
通过使用std::ostream&
,我可以将其他流传递给函数:文件流、字符串流、std::cout
等等。我还可以从中创建(派生)一个自定义Logging
类std::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()
到各种设备、字符串或输出通道。
推荐阅读
- opencv - 非自由算法保持 NO Ubuntu 16.04 opencv-3.4.4
- kubernetes - 在 Kubernetes 中使用 Openstreetmap
- maven - maven eclipse插件生成错误的类路径条目
- vba - 循环返回 VBA Powerpoint 中的字体时出现运行时错误
- javascript - Mac 设备中的 Kinetic / Inertia 滚动,JavaScript
- javascript - Promise 和 Fetch 的问题
- excel - 使用 for 循环将范围中的文本粘贴为 OLEObject
- sharepoint - 如何通过在 csom/odata 中装饰用户代理来避免对共享点的限制
- c++ - 为什么不能重载 test2 + test3 的 operator<<?
- python - 如果谜题无法解决,我如何退出数独求解器功能?