有没有办法在 C++ 中访问外部作用域中的局部变量? [英] Is there any way to access a local variable in outer scope in C++?

查看:12
本文介绍了有没有办法在 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; 
    }
}

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

这篇关于有没有办法在 C++ 中访问外部作用域中的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆