Why does C ++ resolve the variable name and class name the same way?

#include <iostream> #include <vector> using namespace std; typedef int UINT4; class Hack {}; Hack& operator <(Hack& a , Hack& b) { std::cerr << "1"; return a; } Hack& operator >(Hack& a, Hack& b) { std::cerr << "2"; return a; } int main() { Hack vector; // It SHOULD be OK!? Hack UINT4; // It SHOULD be OK!? Hack v; Hack Hack; // It SHOULD be OK!? Hack = v; // It SHOULD be OK!? // Please stop to think for a moment: What will the following output? vector<UINT4> v; // Oh, my god! The whole world goes mad! return 0; } 
+6
c ++ naming-conventions
source share
2 answers

Heard about after ? Look at the parameter types :)

 int stat(const char *path, struct stat *buf); 

What you showed in your question is really not too dramatic. You declare a variable name in the local scope, but the type names in your program are in the global scope. Now I will show you the real perverse thing:

 int nooo = 0; int main() { int nooo = 0; } 

W00t? Why does C ++ allow us to create two variables with the same name!?!

OK, I was joking. Now I will introduce you to the real dark sides to mess with duplicate names. Think about what C ++ allows us!

 struct A { int A; // noes! }; AA; // another A! 

In essence, this is all for compatibility with C :)

+6
source share

You ask a question from the point of view, or someone who knows very well that he uses the class name as an identifier for a variable: obviously this is not the best practice.

Now let's look at something else: suppose you don't suspect that in some obscure header file you include the strange typedef int i; . Do you expect it to break the following innocent code?

 int i = 0; 
+6
source share

All Articles