为什么我可以将 ifstream 文件置于 if 条件中?

Why can I put an ifstream file in an if condition?

我正在尝试检查文件是否成功打开。我发现这种方法可以打开要读取的文件:

char path[]="data/configuration.txt";
std::ifstream configFile(path, std::ifstream::in);
if(configFile) {
  std::cout<<"Successfully opened file: "<<path<<std::endl;
} else {
  std::cout<<"Error, Could not open file: "<<path<<std::endl;
}

问题是 if 究竟检查了什么?

因为我还发现了以下检查文件是否打开的方法:

char path[]="data/configuration.txt";
std::ifstream configFile;
configFile.open(path, std::ifstream::in);
if(configFile.is_open()) {
  std::cout<<"Successfully opened file: "<<path<<std::endl;
} else {
  std::cout<<"Error, Could not open file: "<<path<<std::endl;
}

我还有一些其他问题。例如,这两种打开文件的方法有什么区别?另外,这两个 if 条件有什么区别?

我认为这些是最终结果相同的类似方法,因为我可以使用 std::ifstream 方法,例如 is_open 两种打开方法:

std::ifstream configFile(path, std::ifstream::in);
configFile.open(path, std::ifstream::in);

std::ifstream可以contextually convert to bool via std::basic_ios<CharT,Traits>::operator bool,继承自std::basic_ios.

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

请注意,它执行与 std::basic_ifstream<CharT,Traits>::is_open 不同的检查。

Checks if the file stream has an associated file. Effectively calls rdbuf()->is_open().