在C++中,如何访问块内部的本地变量,如果存在与同名的块级变量?

huangapple go评论63阅读模式
英文:

How to access local variable inside the block if there is a block level variable with the same name in c++?

问题

要访问块内的局部变量,如果存在与同名的块级变量。

英文:
#include <iostream>
using namespace std;


int main() {

    int a = 20;     // want to access this variable
    
    {
        int a = 30;
        
        cout << a << endl; 
    }

    return 0;
}

I want to access the local variable inside the block if there is a block-level variable with the same name

答案1

得分: 1

无法访问内部作用域中被相同名称隐藏的块作用域名称。如果您希望从外部块作用域访问 a,则必须删除内部作用域中的 a 声明。

从技术上讲,您可以使用任何间接方式访问命名对象,例如使用引用:

int a = 20;
int& ref = a;

{
    int a = 30;
    std::cout << ref << '\n';
}

但我不建议使用这种解决方案。相反,我建议为每个变量提供一个唯一的名称:

int meaningful_name = 20;
{
    int clearly_a_different_variable = 30;
    std::cout << meaningful_name << '\n';
}
英文:

You cannot access block scope names hidden by the same name in an inner scope. If you wish to access a from the outer block scope, then you must remove the declaration of the a in the inner scope.

Technically, you can access the named object using any form of indirection, for example using a reference:

int a = 20;
int&amp; ref = a;

{
    int a = 30;
    std::cout &lt;&lt; ref &lt;&lt; &#39;\n&#39;; 
}

But, I wouldn't recommend this solution. Instead, I recommend giving a unique name for each variable:

int meaningful_name = 20;
{
    int clearly_a_different_variable = 30;
    std::cout &lt;&lt; meaningful_name &lt;&lt; &#39;\n&#39;;
}

huangapple
  • 本文由 发表于 2023年4月4日 05:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定