英文:
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& ref = a;
{
int a = 30;
std::cout << ref << '\n';
}
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 << meaningful_name << '\n';
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论