数组的引用——用作形参&返回类型时

一、数组的引用

切入:可以将一个变量定义成数组的引用(这个变量和数组的类型要相同)

形式:

	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 }
View Code

运用:把该形参名视为所绑定的数组的名字使用即可。

优点:节省内存消耗,不用拷贝一份数组,直接使用原数组(甚至可以修改原数组)。

助记:我们不妨以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 }
View Code

三、数组的引用——作为返回类型

难点:对应返回类型的写法、怎么使用该返回的引用

知识:因为数组不能被拷贝,所以函数不能返回数组,但可以返回数组的引用(和数组的指针)

先学习一下返回数组的指针,再来看返回数组的引用!

返回数组的引用的写法可以说和返回数组的指针是一毛一样!

写法:

 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(形参);
View Code

运用:返回一个数组的引用怎么用??

 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 }
View Code

助记:既然返回的数组的引用,而它又只是一个名字(不带维度),我们把它视为所引用的数组(在该函数内返回的那个数组)的别名即可。

补充:返回的是数组的引用,那么函数里也应该返回的是数组!

助记:

 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 }
View Code
原文地址:https://www.cnblogs.com/xzxl/p/7661584.html