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;
}

  

原文地址:http://www.cnblogs.com/itniwota/p/16852748.html

发表评论

您的电子邮箱地址不会被公开。