冰楓論壇

標題: [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
  1. int main()
  2. {
  3.   int a = 1;
  4.   int b = a;
  5.   return 0;
  6. }
複製代碼
2. Call by Pointer
  1. void swap(int *address_a, int *address_b) {
  2.   int temp = *address_a ;
  3.   *address_a = *address_b;
  4.   *address_b = temp;
  5. }

  6. int main() {
  7.   int a = 1;
  8.   int b = 0;
  9.   swap(&a, &b); // 傳入a, b的address進行交換
  10.   return 0;
  11. }
複製代碼
3. Call by Reference
  1. void swap(int &address_a, int &address_b) {
  2.   int temp = address_a ;
  3.   address_a = address_b;
  4.   address_b = temp;
  5. }

  6. int main() {
  7.   int a = 1;
  8.   int b = 0;
  9.   swap(a, b); // 傳入a, b的address進行交換
  10.   return 0;
  11. }
複製代碼
使用Call by Pointer跟Call by Reference傳遞參數給函式會實質變更變數數值!




歡迎光臨 冰楓論壇 (https://bingfong.com/) Powered by 冰楓