【问题标题】:Why is declaring a std::ifstream called cin not a compilation error?为什么声明一个名为 cin 的 std::ifstream 不是编译错误?
【发布时间】:2021-04-28 19:54:59
【问题描述】:

最近,我很好奇如果我声明一个名为cinstd::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 &gt;&gt; N 行更改为std::cin &gt;&gt; N,则程序开始尝试从标准输入中读取N(如预期的那样)。

我的问题是,为什么在这种情况下编译器不报错(我编译这个程序的编译器是 GCC 7.5.0)?我在这里是否还有其他误解?

【问题讨论】:

  • 局部变量总是优先于全局变量,对吧?所以代码是完全合法的。不过,我想-Wshadow 没有发出警告有点令人惊讶。
  • 我很确定-Wshadow 会对此发出警告。 “打开你的编译器警告”可能是最好的和最少遵循的建议。
  • @spectras gcc 没有;铿锵声:godbolt.org/z/1K7hMe

标签: c++ ifstream istream ambiguous


【解决方案1】:

不同的变量可以使用相同的标识符:

  • 在不同的命名空间中,并且
  • 在代码块内,内部范围优先于外部范围。

在您的代码中,您可以同时做这两件事。全局对象std::cinmain函数的局部对象cin可以共存,没有问题。

在代码块中声明的名称会在更外部的范围内隐藏相同的名称。在你声明了自己的cin 之后,你需要写std::cin 来获得那个。

【讨论】:

    猜你喜欢
    • 2021-10-15
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 2013-06-16
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多