c++ 引用
- 引用
- 引用符 —— &
- 引用必须进行初始化
- 一旦进行初始化,以后都不会改变其指向
- 使用
- 作为函数的参数 —— 不会占用额外的空间,能提升函数的执行效率
-
#include <iostream> using std::endl; using std::cout; //引用函数作为参数 void swap(int a, int b)//形参,参数传递的方式是值传递-->就是进行复制 {//初始化形参:int a = x;int b = y; int temp = a; a = b; b = temp; }//不会交换x/y的值 //地址传递--》值传递 void swaq(int *pa, int *pb) { int temp = *pa; *pa = *pb; *pb = temp; }//地址传递 //引用传递 //好处:不会占用额外的空间,能够提升执行效率 void swal(int & ref1, int & ref2) {//形参初始化:int & ref1 = a;int & ref2 = b; int temp = ref1; ref1 = ref2; ref2 = temp; } int main() { int x = 10; int y = 20; cout << "x = " << x << endl; cout << "y = " << y << endl; swap(x , y);//实参 cout << "进行交换之后" << endl; cout << "x = " << x<< endl; cout << "y = " <<y<<endl; swaq(&x,&y);//实参 cout << "进行交换之后" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; swal(x, y);//实参 cout << "进行交换之后" << endl; cout << "x = " <<x<< endl; cout << "y = " <<y<< endl; system("pause"); return 0; }
- 引用可以作为函数的返回值
-
- 当return语句执的时候,也不会进行复制,会返回变量本身
-
#include <iostream> using std::endl; using std::cout; int arr[5] = { 0,1,2,3,4 }; int & func(int idx) { return arr[idx]; } int main() { func(0) = 10; cout << arr[0] << endl; system("pause"); return 0; }
-
注意
-
不要返回一个局部变量的指针/引用,因为当函数结束时这个局部变量的生命周期也会结束
- 不要返回一个指向堆空间变量引用,除非有很好的回收策略
-
-
- 引用可以作为函数的返回值
-
- 作为函数的参数 —— 不会占用额外的空间,能提升函数的执行效率
浙公网安备 33010602011771号