gpt4 book ai didi

c++ - (ostream& outs) 在类函数参数 C++

转载 作者:行者123 更新时间:2023-11-28 06:07:42 25 4
gpt4 key购买 nike

类函数中的参数 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;
}

为什么输出信息到ouput上不再用cout,而是用outs了?

最佳答案

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

基本上,ostream 是要写入的流,将数据输出到某处。 cout 也是一个 ostream。但您也可以将文件作为 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;
}

关于c++ - (ostream& outs) 在类函数参数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32035759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com