pass by value
int main() {
int x = 10;
....
cout << increment(x) << endl;
cout << x << endl;
return 0;
}
int increment(int n) {
n = n + 1;
return n;
}
// x, n 有各自的 memory address,互不影響
pass by address
int main() {
int x = 10;
....
cout << increment(&x) << endl;
cout << x << endl;
return 0;
}
int increment(int *n) {
*n = *n + 1;
return *n;
}
// 使用取址運算子 & 將 x 變數的記憶體位址取出並傳遞給指標 n ( n 指標指向 x 的位址 )
// 接著用 * 來取得此記憶的位址的值。
x_address <- n
*n = x_value
pass by reference (C can't)
int main() {
int x = 10;
....
cout << increment(x) << "\n";
cout << x << "\n";
return 0;
}
int increment(int &n) {
n = n + 1;
return n;
}
int x = 10;
....
cout << increment(x) << "\n";
cout << x << "\n";
return 0;
}
int increment(int &n) {
n = n + 1;
return n;
}
// int & 為參考宣告,呼叫 function 時,不是利用 & 取得 x 的位址
// 而是 n 會自動參考至 x 變數的位址,所以 x 和 n 變數的位址是相同的
pass by reference 可保留參數變動的結果,但若不想參數有變動的話可加上 const
ex. void function(const type *value) {}
pass by address 若要取得兩個以上的運算結果
參考資料:良葛格 http://caterpillar.onlyfun.net/Gossip/CppGossip/PassBy.html



沒有留言:
張貼留言