6.引用

来源:互联网 发布:u盘数据恢复公司 编辑:程序博客网 时间:2024/06/05 04:11

使用引用

 #include "iostream" using namespace std; int main (void){    int a =7,b=8;    int & c=a;//引用变量c相当于a的别名,引用赋值时必须初始化     int & d=b;    cout<<"value a is: "<<a<<endl;    cout<<"value b is: "<<b<<endl;    cout<<"value & of a is c: "<<c<<endl;    cout<<"value & of b is d: "<<d<<endl; }

引用做函数参数

 #include "iostream" using namespace std; void add(int &a,int &b);//  void add1(const int &a,const int &b); int main (void){    int a =7,b=8;    int & c=a;//引用变量c相当于a的别名,引用赋值时必须初始化     int & d=b;    cout<<"value a is: "<<a<<endl;    cout<<"value b is: "<<b<<endl;    cout<<"value & of a is c: "<<c<<endl;    cout<<"value & of b is d: "<<d<<endl;    add(a,b);     cout<<"value a is: "<<a<<endl;    add1(a,b);    cout<<"value a is: "<<a<<endl; }void add(int &a,int &b)//不加 const限定形参 引用相当于解指针 ,相当于地址传递 {    a+=b;    cout<<"result is : "<<a<<endl;}void add1(const int &a,const int &b)//加了const限定形参 引用相当于值传递 ,此时函数定义内不可更改引用的值 {    int temp=a+b;                        cout<<"result is : "<<temp<<endl;}

引用做函数反回值

 #include "iostream" using namespace std;int& add(int &a,int &b) ;// const int& add1(const int &a,const int &b);const int & add2(const int &a,const int& b); int main (void){    int a =7,b=8;    int & c=a;//引用变量c相当于a的别名,引用赋值时必须初始化     int & d=b;    cout<<"value a is: "<<a<<endl;    cout<<"value b is: "<<b<<endl;    cout<<"value & of a is c: "<<c<<endl;    cout<<"value & of b is d: "<<d<<endl;    cout<<"add(a,b) result is: "<<add(a,b)<<endl;    //cout<<"add1(a,b) result is:"<<add1(a,b)<<endl;    cout<<"add2(a,b) result is: "<<add2(a,b)<<endl; }int& add(int &a,int &b) //返回引用 {    int &c=a;//在函数内部声明引用,仍然影响传递过来的引用    c+=b;    int d=c;     d+=b;    return d;}const int& add1(const int &a,const int &b){    int temp=a+b;                        return temp;  //注意,这个temp变量在函数定义中声明,函数返回后temp将不存在,但却返回了一个temp的不可修改的引用 ,这会导致严重错误 }const int & add2(const int &a,const int& b){    return a+b;}
0 0
原创粉丝点击