c++ - `ofstream` 与 0 相比

标签 c++ visual-c++ visual-studio-2019 implicit-conversion ofstream

我正在升级现有的旧代码以使用 VS 2019*,在代码中我有以下函数在返回行失败:

int foo(const char *fn) const
{
    ofstream out(fn,ios::binary);
    if (out)
    {
        //...
    }
    return out!=0;
}

我得到的错误是:

Error C2678 binary '!=': no operator found which takes a left-hand operand of type 'std::ofstream' (or there is no acceptable conversion)



原始诗人的意图是什么,解决问题的最佳方法是什么?

*此代码在 VS 2010 上编译成功。

最佳答案

我想随着升级,您将切换到 C++11 模式。

在 C++11 之前, std::basic_ios ( std::basic_ofstream 的基类)可以转换为 void*含蓄地。

Returns a null pointer if fail() returns true, otherwise returns a non-null pointer.



然后out!=0正在检查流是否没有错误并准备好进行进一步的 I/O 操作。

从 C++11 开始,只有一种转换运算符可以转换 std::basic_iosbool .请注意,运算符标记为 explicit ,因此 out!=0 不允许隐式转换.

您可以将代码更改为 !!out (调用 operator! ),或 !out.fail() , 或 static_cast<bool>(out) (通过 operator bool 显式转换)。

关于c++ - `ofstream` 与 0 相比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59661525/

相关文章:

c++ - 仅在 Release模式下堆损坏

debugging - 如何在调试器中获得数据结构的良好 View ?

c++ - 请解释此类构造函数的输出

C++ 堆碎片分配错误?

visual-studio - 如何在 Visual Studio 2019 中撤消 "Exclude From Project"?

c# - 重命名 Blazor 组件文件名时出现错误

visual-studio - 生成 SSH key 时出错。请检查环境是否配置正确

c++ - IO流是否可移植

c++ - Xcode 链接器错误 : ld: library not found for -twsapi

c++ - 积分推广与运营商+=