【问题标题】:optional ofstream parameter in C++C++ 中的可选 ofstream 参数
【发布时间】:2013-01-26 11:48:46
【问题描述】:

如何使 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;

有什么好主意吗?

【问题讨论】:

    标签: c++ ofstream optional-arguments


    【解决方案1】:

    只需使用ostream:

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

    这适用于任何流类型,不仅适用于fstream,还适用于cout。以及其他流类型,例如ostringstream

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2011-03-04
      • 2010-10-08
      相关资源
      最近更新 更多