繁体   English   中英

类函数参数C ++中的(ostream&outs)

[英](ostream& outs) in class function parameters C++

类函数ostream& outs中的参数是什么意思? 例如

void BankAccout::output(ostream& outs){

    outs.setf(ios::fixed);

    outs.setf(ios::showpoint);

    outs.precision(2);

    outs<<"account balance $"<<balance<<endl;

    outs<<"Interest rate"<<interest_rate<<"%"<<endl;
}

为什么将信息输出到输出而不使用cout而是使用outs?

使自己熟悉流: http : //www.cplusplus.com/reference/iolibrary/

基本上,ostream是要写入的流,将数据输出到某个地方。 cout也是源源不断。 但是您也可以将文件作为ostream打开。 因此,此功能使您可以决定将数据写入何处。 如果要将数据写入终端,则可以将cout作为参数传递。 如果要将其存储在文件中,则可以将文件作为ostream打开,然后将其传递给函数。

例如:

int main(void)
{
  BankAccount *ba = new BankAccount();
  ba->output(cout); //prints to terminal
  std::ofstream ofile; //ofstream is derived from ostream
  ofile.open("test.txt");
  ba->output(ofile); //will output to the file "test.txt"
  delete ba;
  return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM