C++ Nested Scope Accessing

2019-05-26 06:55发布

问题:

I recently saw this code in cppreference:

string str="global scope";

void main()
{
    string str="main scope";
    if (true){
        string str="if scope";
        cout << str << endl;
    }
    cout << str << endl;
}

Which outputs:

if scope
main scope

This is fine, I understand the whole nested scope thing, and I know that the 'str' inside the if scope will be destroyed when the stack unwinds it at the end of the statement, so it wont be available after that, hence the second print takes the main 'str' as its argument.

However, I know that the main 'str' is in fact available inside the IF, or at least it should be, but the question is how can I access the main 'str' from inside the IF statement?

And how could I access a global 'str' from inside the main and/or the if?

I know it would be simpler to just use different names, but this question is not for a specific practical application, but rather for a better understanding of c++ scopes.

回答1:

This is a name-hiding issue. And

how can I access the main 'str' from inside the IF statement?

Unfortunately it's impossible. There's no way to access these local names being hiden.

And how could I access a global 'str' from inside the main and/or the if?

You can use scope resolution operator :: for it, e.g. ::str, which refers to the name str in the global scope.



回答2:

The if block can't refer to the str variable that is defined in main(), unless you change the name of one of the variables. Accessing outer variables of the same name as inner variables is not possible.

However, global variables can be accessed using the :: operator.

Although, a work around is possible using pointers:

string str = "global-scope";

void main()
{
    string str = "main scope";
    string *ptrOfStr = &str;
    if (true){
        string str = "if scope";
        cout << str << endl;
        cout << "Value of str in main block : " << *ptrOfStr;
    }
    cout << str << endl;
}