刚才看了Core Java™ 2 Volume I第四章中的Method Parameters这节,这里又谈起了经典的参数传递问题.综合自己的理解和网上查到的资料在这里总结一下.
首先看看什么叫Call by value(按值传递),什么叫Call by reference(按引用传递).
书上这么说:
The term call by value means that the method gets just the value that the caller provides. In contrast, call by reference means that the method gets the location of the variable that the caller provides. Thus, a method can modify the value stored in a variable that is passed by reference but not in one that is passed by value.
c语言 中, 大家习惯上说有两种参数传递方式,一种按值传递,一种按地址传递.但事实上只有一种按值传递,所谓的按地址传递也就是传了地址的址.(所以严格来说根本没 有一种传参数的方法叫做按地址传递.人们把call by reference硬加到了c语言里并翻译成了按地址传递.)
//可以通过这个例子理解
#include<stdio.h>
swap(int* a, int* b)
{
int *temp;
printf("%x/n",a);
temp = a;
a = b;
b = temp;
printf("%x/n",a); //在swap函数里地址的值交换了
}
main()
{
int a = 10, b = 20;
printf("%x/n",&a); //打印存放a这个变量的地址
swap(&a,&b);
printf("%d,%d/n",a,b);
printf("%x/n",&a); //回到主函数后还那样
getch();
}
c++语言 中 有引用,也就是别名机制,这里才真正有Call by reference.(core java里是这么说的,但是翁恺说其实c++里的传引用实质也是传值,即c语言以后的语言都是传值了,不知道怎么会和这书有出入,而我根本没学过c语言之 前的语言...所以没见识过翁恺所说的真正的传引用,不能和c++里的这个引用作比较,也就没发言权了...)
即如果调用swap(a,b);则能交换a,b里存的值
swap(int& a, int& b)
{
int temp;;
temp = a;
a = b;
b = temp;
}
java语言 中只有按值传递.但是java中有两类数据类型,Primitive types和Object,操纵Object的也被叫做reference,所以就有人以为当传递Object时是Call by reference.其实还是传递的这个reference的副本.
书上说的好:
Let's try to write a method that swaps two employee objects:
public static void swap(Employee x, Employee y) // doesn't work
{
Employee temp = x;
x = y;
y = temp;
}
If the Java programming language used call by reference for objects, this method would work:
Employee a = new Employee("Alice", . . .);
Employee b = new Employee("Bob", . . .);
swap(a, b);
// does a now refer to Bob, b to Alice?
However, the method does not actually change the object references that are stored in the variables a and b. The x and y parameters of the swap method are initialized with copies of these references. The method then proceeds to swap these copies.
// x refers to Alice, y to Bob
Employee temp = x;
x = y;
y = temp;
// now x refers to Bob, y to Alice
But ultimately, this is a wasted effort. When the method ends, the parameter variables x and y are abandoned. The original variables a and b still refer to the same objects as they did before the method call
java里没有c语言那种指针,那么怎么写出一个能交换值的函数呢?
Call by value VS. Call by reference.
最新推荐文章于 2021-10-09 16:22:26 发布