简体   繁体   中英

(ostream& outs) in class function parameters C++

What does the parameter in a class function ostream& outs mean? eg

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;
}

and why is it that for outputing information onto ouput,it no longer uses cout,but now uses outs?

Make yourself familiar with streams: http://www.cplusplus.com/reference/iolibrary/

Basically ostreams are streams to write into, that output the data somewhere. cout is also an ostream. But you can also open a file as an ostream. So this function lets you decide where the data should be written to. If you want the data written in the terminal you pass cout as the argument. If you want it in a file, you open a file as an ostream and pass that to the function instead.

Just for example:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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