#include "iostream"usingnamespacestd;
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"usingnamespacestd;
void add(int &a,int &b);// void add1(constint &a,constint &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(constint &a,constint &b)//加了const限定形参 引用相当于值传递 ,此时函数定义内不可更改引用的值
{
int temp=a+b;
cout<<"result is : "<<temp<<endl;
}
引用做函数反回值
#include "iostream"usingnamespacestd;
int& add(int &a,int &b) ;// constint& add1(constint &a,constint &b);
constint & add2(constint &a,constint& 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;
}
constint& add1(constint &a,constint &b)
{
int temp=a+b;
return temp; //注意,这个temp变量在函数定义中声明,函数返回后temp将不存在,但却返回了一个temp的不可修改的引用 ,这会导致严重错误
}
constint & add2(constint &a,constint& b)
{
return a+b;
}