有没有办法在 C++ 中访问外部作用域中的局部变量?

2022-01-04 00:00:00 scope c++

只是出于好奇:如果我有嵌套的作用域,就像在这个示例 C++ 代码中一样

Just out of curiosity: if I have nested scopes, like in this sample C++ code

using namespace std;

int v = 1; // global

int main (void)
{
    int v = 2; // local
    {
        int v = 3; // within subscope
        cout << "subscope: " << v << endl;
        // cout << "local: " << v << endl; 
        cout << "global: " << ::v << endl;
    }
    cout << "local: " << v << endl;

    cout << "global: " << ::v << endl;

}

有没有办法从中间"范围(非全局或本地)访问变量 v 的值 2?

Is there any way to access the variable v with the value 2 from the "intermediate" scope (neither global nor local)?

推荐答案

你可以像这样声明一个新的引用作为别名

You can declare a new reference as an alias like so

int main (void)
{
    int v = 2; // local 
    int &vlocal = v;
    {
        int v = 3; // within subscope
        cout << "local: " << vlocal  << endl; 
    }
}

但我会完全避免这种做法.我花了几个小时来调试这样的构造,因为在调试器中显示的变量因范围而改变,我无法弄清楚它是如何改变的.

相关文章