引用传递

【Java基础】值传递与引用传递的区别?

不想你离开。 提交于 2020-02-28 17:14:50
值传递 值传递, 是指 方法调用时,传递的参数是按值的拷贝传递 。 如: public class ValueTest { public void test(int x){ System.out.println("值传递,x:"+x); } public static void main(String[] args) { int x = 1; new ValueTest().test(x); } } 引用传递 引用传递,是指 方法调用时,传递的参数是按引用进行传递,其实传递的引用的地址,也就是变量所对应的内存空间的地址。 如: public class ReferenceTest { public void test(Rf rf) { System.out.println("引用传递,rf:" + rf); } public static void main(String[] args) { Rf rf = new Rf(1, "张三"); new ReferenceTest().test(rf); } } class Rf { private int id; private String name; public Rf() { } public Rf(int id, String name) { super(); this.id = id; this.name = name; }

引用传递的一个问题,想不通,先留在BLOG里,以后消灭

血红的双手。 提交于 2019-12-09 13:53:29
执行下面一段代码 #include "stdafx.h" void swap(int *a ,int *b) { int *tmp; tmp=a; a=b; b=tmp; } int& swap2(int& a ,int& b) { int tmp; tmp=a; a=b; b=tmp; return a; } void main() { int a,b; a=100; b=200; printf("a:%d,b:%d,&a:%d,&b:%d\n",a,b,&a,&b); swap2(a,b); printf("a:%d,b:%d,&a:%d,&b:%d\n",a,b,&a,&b); //为什么两次&a,&b的值相同? } 结果是 a:100,b:200,&a:3210136,&b:3210124 a:200,b:100,&a:3210136,&b:3210124 值交换了,但是为什么&a,&b没有交换呢?引用传递不是会传递参数的地址吗?为什么参数的值改变了,参数的地址却没有变呢? 看到了这片 文章 ,但是却苦于对汇编指令不了解,琢磨了半天还是感觉很模糊。以下是引用这篇文章的内容 ————————————分割线———————————— 一、 函数参数传递机制的基本理论   函数参数传递机制问题在本质上是调用函数(过程)和被调用函数(过程)在调用发生时进行通信的方法问题