publicclassDemo{publicstaticvoidmain(String[] args){int a =10;int b =20;change(a,b)//a,b为实参System.out.print(a);//10System.out.print(b);//20}publicstaticvoidchange(int x,int y)//x,y为形参{int temp = x;
x = y;
y = temp;}}
上述change()代码等价于:
publicstaticvoidchange(x:10,y:20)//x,y为形参{int x =10;int y =20int temp = x;
x = y;
y = temp;}//该代码并不会实际上改变a,b的值。
注:在C++中,可以向函数传入指针或引用类型来实现对实参的改变。
//声明void change(int* x,int* y){int temp =*x;*x =*y;*y = temp;}//调用:int a =10;int b =20;change(&a,&b)结果:a =20; b =10
void change(int& x,int& y){int temp = x;
x = y;
y = temp;}//调用:int a =10;int b =20;change(a,b);//结果:a = 20; b = 10
分析:
上述change代码等价于:
void change(int& x:a,int& y:b){int& x = a;int& y = b;int temp = x;
x = y;
y = temp;}//故可以实现值的互换。