how to access a specific scope in c++?

2019-08-06 21:47发布

问题:

#include <iostream>
using namespace std;
int x=24 ;
int main()
{
     int x=0;
     {
         int x=5 ;
        ::x= x+2 ;
     }
    cout<<::x<<endl  ;//first 
    cout<<x<<endl ; // second 
    return 0;
} 

in this simple example i'm using code block and i know i can modify the global variables using Scope resolution operator. and i modify the global variable in this example but i wonder if there is a way to modify the variables in specific scope like main function (not necessary the( Scope resolution operator) way ) that mean in this example i need the first output is 24 and the next one 7 . sorry for my english i hope to understand the question

回答1:

The scoping rules of C++ are textual and AFAIK you can't do this, as you can't go putting namespaces inside of functions. But introducing a reference with a unique name may help you as a workaround if you find yourself in a bind like this:

#include <iostream>
using namespace std;
int x = 24;
int main()
{
     int x = 0;
     int & main_outer_x = x;
     {
         int x = 5;
         main_outer_x = x + 2;
     }
    cout << ::x << endl; //first 
    cout << x << endl; // second 
    return 0;
}

That gives you:

24
7

That shouldn't cost any more memory in your generated code, and lets you keep the outer name untouched. Still, likely to be confusing and error prone if you're purposefully having a name collision within a function. This is abstract code so it's hard to criticize, but most concrete code with such a pattern should probably be done another way.



回答2:

There are no means to access variables from a specific scope in C++.

If you declare an object or a variable in the inner scope with the same name as an object or a variable in the outer scope, then for all intents and purposes that outer scope's object or variable is not directly visible in the inner scope.

If you already have a pointer or a reference to the outer scope's object, of course, you can still access it indirectly. You just cannot access it directly.

This is a fundamental concept of C and C++; but many other programming languages share the same analogous concept.



标签: c++ scope