`ofstream` 与 0 相比

`ofstream` compared to 0

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

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_iosstd::basic_ofstream 的基础 class)可以隐式转换为 void*

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

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

从C++11开始,只有一种转换运算符可以将std::basic_ios转换为bool。请注意,运算符被标记为 explicit,因此 out!=0.

不允许隐式转换

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

classstd::basic_ios中有两个运算符可以应用在这种情况下。他们是

explicit operator bool() const; 
bool operator!() const; 

所以你可以写

return bool( out );

return !!out;

return !out != true;