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

5 c++ fstream

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

std::fstream fileStream;
fileStream.open("somefile.ext");

if (!fileStream)  // How does this work?
  std::cout << "File could not be opened...\n";
Run Code Online (Sandbox Code Playgroud)

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

jli*_*jli 5

它不是真的等于真或假,而是它使!操作员重载以返回其状态.

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

自己这样做非常简单,请查看运算符重载faqC++运算符重载指南.

编辑:有人向我指出,它ios也会重载void *转换运算符,在发生故障时返回空指针.所以你也可以使用这种方法,也包含在前面提到的常见问题中.

  • 它不会重载`operator!`,它使用转换运算符`operator bool` (2认同)