if (!ifstream) 在 C++ 中是什么意思?

what does if (!ifstream) mean in c++?

我找到了这段代码,但我不知道 !ist 是什么意思。


#include <iostream>
#include <fstream>
using namespace std;
#include <string>
int main()
{
    string readname;
    cin >> readname;
    ifstream ist{ readname };
    if (!ist)
    {
        //insert any text here
    }
}

我不知道 (!ist) 的用途。我试图弄清楚这意味着什么,但我不能。

! 是布尔值 "not" 运算符,所以这会测试 ist 以查看它是否 not 有效 - 如果失败能够打开指定的文件并从中读取。

std::basic_ifstream inherits std::basic_ios<CharT,Traits>::operator bool:

Checks whether the stream has no errors.

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

因此代码等效于(以下所有内容):

if (!static_cast<bool>(ist))
if (!ist.operator bool())
if (!!ist.fail())

if (ist.fail())