Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c++ - Why is declaring a std::ifstream called cin not a compilation error?

Recently, I was curious as to what would happen if I declared a std::ifstream called cin, then tried to read input with it. I thought that this would result in a compilation error, because the compiler wouldn't be able to differentiate whether to use the std::istream or the std::ifstream for the input operation. Here's the code I wrote to test this:

#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 << "
";

    return 0;
}

The current code (on my compiler, at least) tries to read N from the file instead of standard input. If I change the cin >> N line to std::cin >> N, however, then the program starts trying to read N from standard input (as expected).

My question is, why doesn't the compiler give an error in this case (the compiler I compiled this program with is GCC 7.5.0)? Is there some other misconception that I'm making here?

question from:https://stackoverflow.com/questions/65877508/why-is-declaring-a-stdifstream-called-cin-not-a-compilation-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The same identifier can be used for different variables:

  • in different namespaces, and
  • inside a code block, with the inner scope overruling the outer scope.

In your code you do both of these things. The global object called std::cin and the local object of main function called cin can coexist with no problem.

A name declared in a code block hides the same name from a more outer scope. After you have declared your own cin, then you would need to write std::cin to get that one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...