In C, we cannot access a global variable if we have a local variable with same name, but it is possible in C++ using scope resolution operator (::).
1 #include<iostream>
2 using namespace std;
3
4 int x; // Global x
5
6 int main()
7 {
8 int x = 10; // Local x
9 cout<<"Value of global x is "<<::x<<endl;
10 cout<<"Value of local x is "<<x;
11 getchar();
12 return 0;
13 }
the C language doesn't have concept of 'resolving scope'. Even C++ can't resolve anonymous scope variables. In C++, since the basic abstraction and encapsulation mechanism (class) can also introduce scope and class variables are possible, a special operator for resolving scope is required. Also, in C++, we can't access function scope variables, nor file scope variables in another file.
For example, see
1 void scope_resolution(void)
2 {
3 static unsigned int i = 2;
4 {
5 static unsigned int i = 1;
6 cout << ::i << endl; // i is looked at global scope
7 }
8 }
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-27 12:17:49