我正在升级现有的旧代码以使用 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()
returnstrue
, 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
显式转换)。
关于c++ - `ofstream` 与 0 相比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59661525/