C++ Nested Scope Accessing

左心房为你撑大大i 提交于 2019-12-06 07:03:22

问题


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;
}


来源:https://stackoverflow.com/questions/41842637/c-nested-scope-accessing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!