標籤:turn 空間 c++ wap 複製 int 實參 code 改變
- 引用
- 引用符 —— &
- 引用必須進行初始化
- 一旦進行初始化,以後都不會改變其指向
- 使用
- 作為函數的參數 —— 不會佔用額外的空間,能提升函數的執行效率
#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;}
c++ 引用