1. 程式人生 > >【基礎】函數的參數傳遞

【基礎】函數的參數傳遞

輸出結果 技術 blog span sin image using 問題 實現

 

#include <iostream>
using namespace std;


int main(){
int x,y;
cin >> x >> y;
int temp;
cout << "Before swap a and y:" << endl;
cout << x << " "<< y << endl;

temp = x;
x = y;
y = temp;


cout << "After swap x and y:" << endl;
cout << x << " " << y << endl;


return 0;
}

這是一段用於交換輸入的兩個整數的值的代碼,測試一下

輸入數據:

13 21

輸出結果:

Before swap a and y:
13 21
After swap x and y:
21 13

沒有任何問題

因為要交換多組數據,我們把交換的代碼改寫成用 函數 實現

#include <iostream>
using namespace std;

void swap(int x, int y);

int main(){
    int x,y;
    cin >> x >> y;

    cout << "
Before swap a and y:" << endl; cout << x << " " << y << endl; swap(x,y); cout << "After swap x and y:" << endl; cout << x << " " << y << endl; return 0; } void swap(int x, int y){ int temp; temp = x; x
= y; y = temp; }

輸入數據:

13 21

輸出結果:

Before swap a and y:
13 21
After swap x and y:
13 21

改寫後的代碼並沒有交換 x,y 的值,回想下剛剛的思路

技術分享圖片

其實,這種思路數據是錯誤的

C++的函數的參數方式是 值傳遞 ,swap 函數在被調用時,系統會給形參分配空間,用實參的值初始化 swap 的 x,y

技術分享圖片

通過上圖我們可以看到,函數的值傳遞是單向的(註意:變量名只是個代號,重要的是它所指向的東西)

那麽要怎麽樣才能在 swap 函數交換 main 函數的 x,y呢?

我們可以使用 引用傳遞 的方式對函數的參數進行傳遞

引用 是一種 特殊類型 的 變量 ,相當於給 變量 起一個 別名 ,來看下下面的代碼

/*
*摘 要:引用傳遞示例
*作 者:水汐音
*完成日期:2018年2月27日
*/
#include <iostream>
using namespace std;

int main(){
    int x,y;
    
    x = 3;
    y = 4;

    cout << "Before:" << endl;
    cout << x << " " << y << endl;

    int &b = x;
    b = y;

    cout << "After:" << endl;
    cout << x << " " << y << endl;

    return 0;
}

輸出結果

Before:
3 4
After:
4 4

可以看到,b 作為 x 的別名,改變變量 b 的值 就是改變變量 x 的值

打個比方,我們假設 李華 的小名是 小華,

別人寄給了小華華一個刀片,跟別人寄給李華一個刀片是一樣的

同理,把 y 的值給了 b,跟把 y 的值給了 x 是一樣的

通過 引用傳遞 我們把 swap 函數 debug

#include <iostream>
using namespace std;

void swap(int &x, int &y);

int main(){
    int x,y;
    cin >> x >> y;

    cout << "Before swap a and y:" << endl;
    cout << x << " " << y << endl;
    
    swap(x,y);

    cout << "After swap x and y:" << endl;
    cout << x << " " << y << endl;

    return 0;
}

void swap(int &x, int &y){
    int temp;
    temp = x;
    x = y;
    y = temp;
}

輸入數據:

13 21

輸出結果:

Before swap a and y:
13 21
After swap x and y:
21 13

成功交換

註意: & 既可以表示引用,又可以 表示取地址符

int a = 9;
int &na = a; //定義引用
int *p = &a; //取地址

                                                  2018-02-27

                                                    水汐音

【基礎】函數的參數傳遞