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

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

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

问题

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

英文:
  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int a = 20; // want to access this variable
  5. {
  6. int a = 30;
  7. cout << a << endl;
  8. }
  9. return 0;
  10. }

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 声明。

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

  1. int a = 20;
  2. int& ref = a;
  3. {
  4. int a = 30;
  5. std::cout << ref << '\n';
  6. }

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

  1. int meaningful_name = 20;
  2. {
  3. int clearly_a_different_variable = 30;
  4. std::cout << meaningful_name << '\n';
  5. }
英文:

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:

  1. int a = 20;
  2. int&amp; ref = a;
  3. {
  4. int a = 30;
  5. std::cout &lt;&lt; ref &lt;&lt; &#39;\n&#39;;
  6. }

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

  1. int meaningful_name = 20;
  2. {
  3. int clearly_a_different_variable = 30;
  4. std::cout &lt;&lt; meaningful_name &lt;&lt; &#39;\n&#39;;
  5. }

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:

确定