CPP Learning: 引用变量和引用形参

程序源码

#include <iostream>
using namespace std;

//无法完成交换的功能
void swap(int x, int y){
    cout << "Before: ";
    cout << x << '\t' << y << endl;
    int t = x;
    x = y;
    y = t;
    cout << "After:  ";
    cout << x << '\t' << y << endl;
}

//C语言里面的写法
void swapc(int *x, int *y){
    int t = *x;
    *x = *y;
    *y = t;
}

//C++的引用变量
void swapcpp(int &x, int &y){
    int t = x;
    x = y;
    y = t;
}

//用处
int main(void){

    #if 0
    int a = 3;
    int &r = a; //定义的时候指明引用的是谁,类型要匹配
    cout << a << '\t' << r << endl;
    r = 4;
    cout << a << '\t' << r << endl;
    #endif

    #if 1
    int a = 3, b = 4;
    cout << a << '\t' << b << endl;
    swap(a,b);
    cout << a << '\t' << b << endl;
    swapc(&a,&b);
    cout << a << '\t' << b << endl;
    swapcpp(a,b);
    cout << a << '\t' << b << endl;
    #endif

    return 0;
}

运行结果

 

THE END
分享
二维码
海报
CPP Learning: 引用变量和引用形参
程序源码 #include <iostream> using namespace std; //无法完成交换的功能 void swap(int x, int y){ cout << "Before: "; cout ……