有没有什么方法访问C ++中外部范围的局部变量? [英] Is there any way to access a local variable in outer scope in C++?

查看:131
本文介绍了有没有什么方法访问C ++中外部范围的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是出于好奇心:如果我有嵌套的范围,像这个示例C ++代码

  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

 您可以将新引用声明为别名, int main(void)
{
int v = 2; // local
int& vlocal = v;
{
int v = 3; // within subscope
cout<< local:< vlocal< endl;
}
}

但我会避免这种做法。我花了几个小时调试这样一个结构,因为一个变量显示在调试器中,因为范围的改变,我不知道它是如何改变。


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;

}

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

But I would avoid this practice this altogether. I have spent hours debugging such a construct because a variable was displayed in debugger as changed because of scope and I couldn't figure out how it got changed.

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

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