【发布时间】:2017-10-07 11:17:31
【问题描述】:
谁能解释一下这里发生了什么...?
我有这个代码:
#include <fstream>
#include <string>
#include <iostream>
int main(){
std::ifstream file("test.txt");
std::string x;
while (true) {
if (!(file >> x)) return 0;
std::cout << x << "\n";
}
}
...编译得很好,做它应该做的,到目前为止没有问题。有时候我不太喜欢!,因为它很容易被忽略,所以我把if换成了
if ((file >> x)==false) return 0;
..突然我的编译器 (gcc 4.8.5) 发出警告:
warning: converting ‘false’ to pointer type ‘void*’ [-Wconversion-null]
if ((file >> x)==false) return 0;
这就是我开始感到困惑的地方。 void* 来自哪里? >> 不会返回一个应该转换为bool 的引用吗?为什么false 转换为void*?为什么我没有明确写false时没有触发相同的警告?
出于好奇,我也试过这个:
if ((file>>x)==true) return 0;
这会导致以
开头的错误风暴error: no match for ‘operator==’ (operand types are ‘std::basic_istream<char>’ and ‘bool’)
if ((file>>x)==true) return 0;
^
现在我完全迷路了。 false 与 bool 与 true 有何不同?当然不同的值,但我一直认为true和false是同一类型。
【问题讨论】:
-
void *重载已在 C++11 中删除,我建议使用现代 C++ -
@M.M 你确定吗?使用
-std=c++11编译时,我得到完全相同的警告。也许 gcc 忘了删除它 -
听起来像是编译器错误
标签: c++ stream boolean type-conversion