c++ 引用作为参数传递

//值传递
void swap(int a , int  b){
    
    int tmp = a;
    
    a = b ;
    
    b = tmp ;
    
    cout << "swap a " << a << endl;
    
    cout << "swap b " <<  b << endl;
}
//地址传递
void swap2(int *a , int  *b){
    
    int tmp = *a;
    
    *a = *b ;
    
    *b = tmp ;

}
//引用传递
void swap3(int &a , int  &b){
    
    int tmp = a;
    
    a =b;
    
    b = tmp;

}

int main() {

    int a = 10 ;
    
    int  b =20 ;
    
    swap(a, b);
    
    cout << "a " << a << endl;
    
    cout << "b " <<  b << endl;
    
    int c = 10;
    
    int d = 20;
    
    swap2(&c, &d);
    
    cout << "c " << c << endl;
    
    cout << "d " <<  d << endl;
    
    int e = 10;
    
    int f = 20;
    
    swap3(e, f);
    
    cout << "e " << e << endl;
    
    cout << "f " <<  f << endl;
    
    return 0;
}

  

posted on 2022-11-02 22:17  知了不了了之  阅读(14)  评论(0编辑  收藏  举报