内容
1.引用的概念
2.引用做函数参数
3.引用做函数返回值
4.引用的本质
5.常量引用
————————————————————————————————————————————
*1.引用的概念
作用:给变量起别名
语法:数据类型 & 别名 = 原名;
#include<iostream>
using namespace std;
int main(){
int a = 10;
int n = 20;
int &c; //引用变量必须进行初始化
int &c=n; //一旦初始化之后就不可更改
cout << "c=" << c << endl;
c=a; //这是赋值操作,不是更改操作
cout << "a=" << a << endl;
cout << "n=" << n << endl;
cout << "c=" << c << endl;
int &b=a;
cout<<a<<endl;
cout<<b<<endl;
b=20;
cout<<a<<endl;
cout<<b<<endl;
system("pause");
return 0;
}
结果表明:通过给别名重新赋值,可以修改原始值
*2.引用做函数参数
作用:在调用函数传参时,可以利用引用作为函数参数,实现通过形参修改实参
优点:可以简化指针修改实参
#include<iostream>
using namespace std;
//值传递,交换两数的值
void swap_1(int x,int y){
int temp = x;
x = y;
y = temp;
}
//地址传递,通过指针交换两数的值
void swap_2(int *x,int *y){
int temp = *x;
*x = *y;
*y =temp;
}
//引用传递
void swap_3(int &x,int &y){
int temp = x;
x = y;
y = temp;
}
int main(){
int a = 2;
int b = 4;
swap_1(a,b);
cout<<"a:"<<a<<"b:"<<b<<endl;
swap_2(&a,&b);
cout<<"a:"<<a<<"b:"<<b<<endl;
swap_3(a,b);
cout<<"a:"<<a<<"b:"<<b<<endl;
system("pause");
return 0;
}
因为先进行了地址传递,交换过一次,已经修改了实参,接着引用传递,同样可以修改实参。
总结:通过引用参数产生的效果同按地址传递是一样的。引用的语法更清楚简单。
*3.引用做函数返回值
作用:引用可以作为函数的返回值
用法:函数调用作为左值
#include<iostream>
using namespace std;
//返回局部变量引用
int &func1(){
int a=10;
return a;
}
//返回静态变量引用
int &func2(){
static int a=20;
return a;
}
int main(){
int & ret1=func1();
cout<<"ret1="<<ret<<endl;
cout<<"ret1="<<ret<<endl;
int & ret2=func2();
cout<<"ret2="<<ret2<<endl;
cout<<"ret2="<<ret2<<endl;
func2()=30; //引用作为函数的返回值时,此时该函数的函数调用可以作为左值存在
cout<<"ret2="<<ret2<<endl;
sysytem("pause");
return 0;
}
注意:不要返回局部变量的引用,因为函数调用完后,栈区的函数参数和局部变量已经被释放掉了。
int & ret1=func1(); //将函数返回值(此时函数的返回值是一个引用类型的)赋值给一个引用(别名)=> &ret = &a;
cout<<“ret1=”<<ret<<endl;第一次能够访问,是因为编译器做了一次保留,第二次就看不到结果了。
*4.引用的本质
本质:在C++内部,引用实际是一个指针常量 指针概念跳转链接
#include<iostream>
using namespace std;
//引用实际上是一个指针常量(指针的指向不可改变,值可以改变) 转换为 int* const ref = &a;
void func(int& ref){
ref = 100; // ref是引用,转换为*ref = 100
}
int main(){
int a = 10;
int b = 5;
//自动转换为 int* const ref = &a; 指针常量是指针指向不可改,也说明为什么引用不可更改
int& ref = a;
//int& ref = b; //编译错误,引用不可更改
ref = 20; //内部发现ref是引用,自动帮我们转换为: *ref = 20;
cout << "a:" << a << endl;
cout << "ref:" << ref << endl;
func(a);
return 0;
}
*5.常量引用
作用:常量引用主要用来修饰形参,防止误操作
用法:在函数形参前加上const修饰,防止形参修改实参
- int& b = 10;
- //会报错!定义引用时直接赋值是错误的,引用本身需要一块合法的内存空间
- const int& b = 100;
- //加上const之后不报错,是因为编译器内部自动优化代码,int temp = 100; const int& ref = temp;
#include<iostream>
using namespace std;
void add1(const int & x){
x=x+1; //会报错,显示x为不可修改的
}
void add2(int & y){
y=y+2;
}
int main(){
int a=1;
cout<<"a:"<<a<<endl;
add1(a);
cout<<"a:"<<a<<endl;
add2(a);
cout<<"a:"<<a<<endl;
system("pause");
return 0;
}
加上const 修饰引用作为函数形参,防止函数修改形参进而修改实参。
引用作为函数参数,形参的改变会导致实参也改变。