块中 java 变量的作用域是什么? [英] What is the scope of a java variable in a block?
本文介绍了块中 java 变量的作用域是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在 C++ 中变量有块作用域,例如下面的代码在 C++ 中有效
void foo(){int a = 0;for(int i = 0; i <10; ++i){int a = 1;//在这里重新定义一个.}
}
但是这个片段在java中不起作用,它报告重复的局部变量a",这是否意味着java变量没有BLOCK范围?
解决方案
java 变量确实有一个块作用域,但是如果你注意到 int a 已经在作用域中定义了
<预> {int a = 0;{{}}}所有子范围都在最上面的大括号的范围内.因此,您会收到重复的变量错误.
I know in c++ variables have block scope, for example, the following code works in C++
void foo(){
int a = 0;
for(int i = 0; i < 10; ++i){
int a = 1; //re-define a here.
}
}
but this snippet doesnt work in java, it reports "duplicate local variable a", does it mean java variables dont have BLOCK scope?
解决方案
java variables do have a block scope but if you notice int a is already defined in scope
{ int a = 0; { { } } }
all subscopes are in scope of the uppermost curly braces. Hence you get a duplicate variable error.
这篇关于块中 java 变量的作用域是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文