if('fstream 对象')如何返回 true 或 false 的值,具体取决于文件是否已打开?

How does if ('fstream object') return a value of true or false depending on if the file was opened?

本文关键字:取决于 文件 是否 true 何返回 对象 fstream 返回 false if 的值      更新时间:2023-10-16

我很好奇fstream class如何通过简单地将对象的名称放在条件语句中来返回truefalse值。例如。。。

std::fstream fileStream;
fileStream.open("somefile.ext");
if (!fileStream)  // How does this work?
  std::cout << "File could not be opened...n";

问这个是因为如果我以类似的方式使用它,我希望我自己的类返回一个值。

这并不是说它等于真或假,而是它重载了!运算符以返回其状态。

有关详细信息,请参阅 http://www.cplusplus.com/reference/iostream/ios/operatornot/。

自己执行此操作非常简单,请查看运算符重载常见问题解答或C++运算符重载指南。

编辑:有人向我指出,ios还会重载void *转换运算符,在失败时返回空指针。因此,您也可以使用这种方法,前面提到的常见问题解答中也介绍了这种方法。

这使用转换运算符工作。请注意,看似显而易见的方式,转换为bool,具有意想不到的副作用,因此应使用转换为内置类型并隐式转换为bool,例如:

class X
{
public:
  void some_function(); // this is some member function you have anyway
  operator void(X::*)() const
  {
    if (condition)
      return &X::some_function; // "true"
    else
      return 0; // "false"
  }
};

在 C++11 中,您可以转换为显式bool,从而避免意外的副作用。因此,在 C++11 中,您可以简单地编写:

class X
{
public:
  explicit operator bool() const
  {
    return condition;
  }
};