引用的使用方法,引用传递

#include <bits/stdc++.h>

using namespace std;

int main()
{
    //1.引用必须初始化
    int a = 10;
//    int &b;   error:'b'decleared but not initialized
    int &b = a;
    b+=10;
    cout<<"a="<<a<<endl;
    cout<<"b="<<b<<endl;
    //2.引用一旦初始化就不能更改了
    int c = 50;
//    &b = c;   error:lvalue required as left operand of assignment

    //结束
    return 0;
}
#include <bits/stdc++.h>

using namespace std;

void swap1(int x, int y){//值传递
    swap(x,y);
}
//地址传递(略)
void swap2(int &x, int &y){//引用传递
    swap(x,y);
}

int main()
{
    int a=10,b=20;
    swap1(a,b);
    cout<<"swap1:"<<"a="<<a<<",b="<<b<<endl;
    swap2(a,b);
    cout<<"swap2:"<<"a="<<a<<",b="<<b<<endl;

    //结束
    return 0;
}

上一篇:递归和递推(一)


下一篇:上台阶