最近,我很好奇,如果我声明了一个名为std::ifstream的cin,然后尝试用它读取输入,会发生什么。我认为这会导致编译错误,因为编译器无法区分输入操作是使用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编译这个程序的编译器)?我在这里还有别的误解吗?
发布于 2021-01-25 00:38:35
相同的标识符可以用于不同的变量:
在您的代码中,您可以同时完成这两项任务。名为std::cin的全局对象和名为cin的main函数的本地对象可以共存,没有问题。
在代码块中声明的名称从更外部的范围中隐藏相同的名称。在声明了自己的cin之后,您将需要编写std::cin才能获得该std::cin。
https://stackoverflow.com/questions/65877508
复制相似问题