【发布时间】:2021-04-28 19:54:59
【问题描述】:
最近,我很好奇如果我声明一个名为cin 的std::ifstream,然后尝试用它读取输入会发生什么。我认为这会导致编译错误,因为编译器无法区分是使用std::istream 还是std::ifstream 进行输入操作。这是我为测试而编写的代码:
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
ifstream cin("math_testprogram.in");
int N;
cin >> N; // I expect this line to result in some sort of
// "reference to cin is ambiguous" error
cout << N << "\n";
return 0;
}
当前代码(至少在我的编译器上)尝试从文件而不是标准输入中读取N。但是,如果我将cin >> N 行更改为std::cin >> N,则程序开始尝试从标准输入中读取N(如预期的那样)。
我的问题是,为什么在这种情况下编译器不报错(我编译这个程序的编译器是 GCC 7.5.0)?我在这里是否还有其他误解?
【问题讨论】:
-
局部变量总是优先于全局变量,对吧?所以代码是完全合法的。不过,我想
-Wshadow没有发出警告有点令人惊讶。 -
我很确定
-Wshadow会对此发出警告。 “打开你的编译器警告”可能是最好的和最少遵循的建议。 -
@spectras gcc 没有;铿锵声:godbolt.org/z/1K7hMe
标签: c++ ifstream istream ambiguous