gpt4 book ai didi

c++ - C++ 中可选的 ofstream 参数

转载 作者:行者123 更新时间:2023-11-30 02:57:14 24 4
gpt4 key购买 nike

如何使 ofstream 参数可选?

bool LookingFor(std::string &mi_name, ofstream &my_file = std::cout)
{
my_file << xxx;
.......

}

上述方法签名的编译错误是:

“std::ofstream& my_file”的类型为“std::ostream {aka std::basic_ostream}”

我正在使用 mingw32。

我希望此函数在没有第二个参数时写入控制台。我尝试了无数的事情,但没有任何效果。我不介意是否必须检查代码以查看它是否打开,例如:

if(my_file.isopen())
my_file << xxx;
else
cout << xxx;

有什么好主意吗?

最佳答案

只需使用ostream:

bool LookingFor(std::string &mi_name, std::ostream &out = std::cout) {
out << xxx;
}

这适用于任何流类型,不仅是fstream,还有cout。和其他流类型,如 ostringstream

关于c++ - C++ 中可选的 ofstream 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14811082/

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