通過引用調用(也稱為引用傳遞)是一種評估策略,其中函式接收對用作參數的變數的隱式引用,而不是其值的副本。這通常意味著該函式可以修改(即分配給)用作參數的變數 - 其調用者將看到的內容。因此,可以使用引用呼叫在被叫功能和呼叫功能之間提供附加的通信信道。調用引用語言使程式設計師更難以跟蹤函式調用的效果,並可能引入細微的錯誤。
基本介紹
- 中文名:按引用傳遞
- 外文名:Call by reference
介紹
例子
def modify(var p, &q) { p := 27 # passed by value: only the local parameter is modified q := 27 # passed by reference: variable used in call is modified}? var a := 1# value: 1? var b := 2# value: 2? modify(a, &b)? a# value: 1? b# value: 27
void modify(int p, int* q, int* r) { p = 27; // passed by value: only the local parameter is modified *q = 27; // passed by value or reference, check call site to determine which *r = 27; // passed by value or reference, check call site to determine which}int main() { int a = 1; int b = 1; int x = 1; int* c = &x; modify(a, &b, c); // a is passed by value, b is passed by reference by creating a pointer (call by value), // c is a pointer passed by value // b and x are changed return 0;}
按引用傳遞的重要特點
public class TempTest { private void test1(A a){ a.age = 20; System.out.println("test1方法中的age="+a.age); } public static void main(String[] args) { TempTest t = new TempTest(); A a = new A(); a.age = 10; t.test1(a); System.out.println(”main方法中的age=”+a.age); } } class A{ public int age = 0; }
test1方法中的age=20 main方法中的age=20