"ostream &os"有什么用?
What's the use of "ostream &os"?
我刚开始学习C++,我在C++入门中看到了一些函数:
double total_receipt(ostream &os)const{...}
然后我试着用这个代码找到cout
的地址:"cout << &cout << endl;"
而CCD_ 3与直接使用CCD_。
那么为什么不直接使用cout
而不是ostream &os
呢?或者这只是一个"好"习惯?
第一个通知:
cout
是一个对象(请查看这些文档(ostream
是一个类(请查看这些文档(
当你声明一个方法时,你需要使用参数的类名,所以如果你的类使用"输出流"(这就是ostream
的意思(,那么你就声明你的函数,比如:
double total_receipt(ostream &os)
你不能创建这样的函数:
double total_receipt(cout) // doesn't work
现在,如果您的问题是关于像这样声明total_receipt
函数与之间的区别
double total_receipt(ostream &os) {
os << "hello world" << std::endl;
}
或者像这样:
double total_receipt() {
std::cout << "hello world" << std::endl;
}
这取决于你。通常,我们使用第一个,因为它允许用cout
之外的其他东西调用函数,比如:
ofstream out_file("my_file.txt");
total_receipt(out_file);
因此,您可以将从ostream
派生的类的任何对象传递给该函数,如示例中的ofstream
。这意味着,除了打印到终端之外,您的功能还可以打印到文件中,因此如果需要,您可以添加更多功能。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- "ostream &os"有什么用?
- 我应该使用什么功能在mac OS X中打开文件
- Mac OS X(CommandLineTools)上的c ++和g ++有什么区别?
- Mac OS X 上的达尔文斯图书馆位置是什么?
- libc++ 标头位于 Mac OS X Mavericks 上的什么位置
- lldb/gdb 有什么问题,忽略 OS X 中的第一个 sleep() 语句?
- 从malloc()进行的Windows和Linux本机OS/系统调用是什么
- 什么会导致ifstream代码在OS X上失败?
- Windows . net (c++) SpinWait在Linux和Mac OS X上的等效是什么?
- 什么可以使纳米睡眠漂移在 mac OS X 10.9 上正好 10.9 秒
- Macintosh OS X Mavericks上的/proc/self/exe是什么?