此Java代码:
public class XYZ {
public static void main(){
int toyNumber = 5;
XYZ temp = new XYZ();
temp.play(toyNumber);
System.out.println("Toy number in main " + toyNumber);
}
void play(int toyNumber){
System.out.println("Toy number in play " + toyNumber);
toyNumber++;
System.out.println("Toy number in play after increement " + toyNumber);
}
}
将输出以下内容:
玩耍中的玩具编号5 递增6后的玩具数量 主玩具号5
在C ++中,我可以将toyNumber
变量作为引用传递,以避免产生阴影,即创建如下相同变量的副本:
void main(){
int toyNumber = 5;
play(toyNumber);
cout << "Toy number in main " << toyNumber << endl;
}
void play(int &toyNumber){
cout << "Toy number in play " << toyNumber << endl;
toyNumber++;
cout << "Toy number in play after increement " << toyNumber << endl;
}
C ++输出将是这样的:
玩耍中的玩具编号5 递增6后的玩具数量 主玩具号6
我的问题是-如果Java是通过值传递而不是通过引用传递,那么Java中与C ++代码获得相同输出的等效代码是什么?
toyNumber
声明的变量main
不在方法范围内play
。在C ++和Java中,只有在合并范围时,才会发生阴影。参见en.wikipedia.org/wiki/Variable_shadowing。