標題: [C++] Call by Value/Call by Pointer/Call by Reference的範例 [打印本頁] 作者: whitefox 時間: 2023-6-12 09:04 標題: [C++] Call by Value/Call by Pointer/Call by Reference的範例 1. Call by Value
int main()
{
int a = 1;
int b = a;
return 0;
}
複製代碼
2. Call by Pointer
void swap(int *address_a, int *address_b) {
int temp = *address_a ;
*address_a = *address_b;
*address_b = temp;
}
int main() {
int a = 1;
int b = 0;
swap(&a, &b); // 傳入a, b的address進行交換
return 0;
}
複製代碼
3. Call by Reference
void swap(int &address_a, int &address_b) {
int temp = address_a ;
address_a = address_b;
address_b = temp;
}
int main() {
int a = 1;
int b = 0;
swap(a, b); // 傳入a, b的address進行交換
return 0;
}
複製代碼
使用Call by Pointer跟Call by Reference傳遞參數給函式會實質變更變數數值!