"ostream &os"有什么用?

What's the use of "ostream &os"?

本文关键字:什么 os ostream      更新时间:2023-10-16

我刚开始学习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。这意味着,除了打印到终端之外,您的功能还可以打印到文件中,因此如果需要,您可以添加更多功能。