一、數組的引用
切入:可以將一個變量定義成數組的引用(這個變量和數組的類型要相同)
形式:
int odd[5] = {1, 3, 5, 7, 9}; int (&arr)[5] = odd; //中括號內的數一定要和所引用的數組的維度一樣 cout << arr[3] << endl; //等價於odd[3]
解讀:注意上面代碼中的形式,因為arr引用了數組odd,故arr變成了數組的別名。
二、數組的引用——作為形參
難點:對應形參/實參的寫法、怎么運用該形參
寫法:

1 #include <iostream> 2 #include <vector> 3 #include <cctype> 4 #include <string> 5 #include <iterator> 6 #include <initializer_list> 7 8 using namespace std; 9 10 void print(int (&arr)[5]) 11 { 12 for (auto i : arr) 13 cout << i << endl; 14 } 15 16 int main() 17 { 18 int odd[5] = {1, 3, 5, 7, 9}; 19 print(odd); 20 return 0; 21 }
運用:把該形參名視為所綁定的數組的名字使用即可。
優點:節省內存消耗,不用拷貝一份數組,直接使用原數組(甚至可以修改原數組)。
助記:我們不妨以string對象的引用來輔助記憶,因為string就像是一個字符數組,只是它沒有確定的容量。

1 #include <iostream> 2 #include <vector> 3 #include <cctype> 4 #include <string> 5 #include <iterator> 6 #include <initializer_list> 7 8 using namespace std; 9 10 //void print(int (&arr)[5]) 11 void print(string &arr) //相比數組,只是少了一個[維度] 12 { 13 for (auto i : arr) 14 cout << i << endl; 15 } 16 17 int main() 18 { 19 // int odd[5] = {1, 3, 5, 7, 9}; 20 string ss = "hello world"; 21 // print(odd); 22 print(ss); 23 return 0; 24 }
三、數組的引用——作為返回類型
難點:對應返回類型的寫法、怎么使用該返回的引用
知識:因為數組不能被拷貝,所以函數不能返回數組,但可以返回數組的引用(和數組的指針)
先學習一下返回數組的指針,再來看返回數組的引用!
返回數組的引用的寫法可以說和返回數組的指針是一毛一樣!
寫法:

1 /* 題目:編寫一個函數的聲明,使其返回包含10個string對象的數組的引用 */ 2 //不用類型別名 3 string (&func(形參))[10]; 4 //類型別名 5 using arrS = string[10]; 6 arrS& func(形參); 7 //尾置返回類型 8 auto func(形參) -> string(&)[10]; 9 //decltype關鍵字 10 string ss[10]; 11 decltype(ss) &func(形參);
運用:返回一個數組的引用怎么用??

1 #include <iostream> 2 #include <vector> 3 #include <cctype> 4 #include <string> 5 #include <iterator> 6 #include <initializer_list> 7 8 using namespace std; 9 10 int odd[] = {1, 3, 5, 7, 9}; 11 int even[] = {0, 2, 4, 6, 8}; 12 13 //int (&func(int i))[5] 14 //auto func(int i) -> int(&)[5] 15 decltype(odd) &func(int i) 16 { 17 return (i % 2) ? odd : even; 18 } 19 20 int main() 21 { 22 cout << func(3)[1] << endl; //輸出3 23 return 0; 24 }
助記:既然返回的數組的引用,而它又只是一個名字(不帶維度),我們把它視為所引用的數組(在該函數內返回的那個數組)的別名即可。
補充:返回的是數組的引用,那么函數里也應該返回的是數組!
助記:

1 int &func(int a, int b) 2 { 3 return a > b ? a : b; 4 } 5 //函數調用結束后,返回b的引用,返回引用的優點在於不用拷貝一個值返回 6 7 int main() 8 { 9 int x = 3, y = 4; 10 int ans = func(x, y); //ans = 4 11 return 0; 12 }