6.引用

本文深入探讨C++中引用的使用方法,包括基本概念、作为函数参数及返回值的应用技巧,并对比值传递与引用传递的区别。

使用引用

 #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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值