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

一、数组的引用

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

形式:

	int odd[5] = {1, 3, 5, 7, 9};
int (&arr)[5] = odd; //中括号内的数一定要和所引用的数组的维度一样
cout << arr[3] << endl; //等价于odd[3]

解读:注意上面代码中的形式,因为arr引用了数组odd,故arr变成了数组的别名。

二、数组的引用——作为形参

难点:对应形参/实参的写法、怎么运用该形参

写法:

 #include <iostream>
#include <vector>
#include <cctype>
#include <string>
#include <iterator>
#include <initializer_list> using namespace std; void print(int (&arr)[])
{
for (auto i : arr)
cout << i << endl;
} int main()
{
int odd[] = {, , , , };
print(odd);
return ;
}

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

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

助记:我们不妨以string对象的引用来辅助记忆,因为string就像是一个字符数组,只是它没有确定的容量。

 #include <iostream>
#include <vector>
#include <cctype>
#include <string>
#include <iterator>
#include <initializer_list> using namespace std; //void print(int (&arr)[5])
void print(string &arr) //相比数组,只是少了一个[维度]
{
for (auto i : arr)
cout << i << endl;
} int main()
{
// int odd[5] = {1, 3, 5, 7, 9};
string ss = "hello world";
// print(odd);
print(ss);
return ;
}

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

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

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

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

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

写法:

 /*    题目:编写一个函数的声明,使其返回包含10个string对象的数组的引用    */
//不用类型别名
string (&func(形参))[];
//类型别名
using arrS = string[];
arrS& func(形参);
//尾置返回类型
auto func(形参) -> string(&)[];
//decltype关键字
string ss[];
decltype(ss) &func(形参);

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

 #include <iostream>
#include <vector>
#include <cctype>
#include <string>
#include <iterator>
#include <initializer_list> using namespace std; int odd[] = {, , , , };
int even[] = {, , , , }; //int (&func(int i))[5]
//auto func(int i) -> int(&)[5]
decltype(odd) &func(int i)
{
return (i % ) ? odd : even;
} int main()
{
cout << func()[] << endl; //输出3
return ;
}

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

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

助记:

 int &func(int a, int b)
{
return a > b ? a : b;
}
//函数调用结束后,返回b的引用,返回引用的优点在于不用拷贝一个值返回 int main()
{
int x = , y = ;
int ans = func(x, y); //ans = 4
return ;
}
上一篇:js关闭子页面刷新父页面


下一篇:nginx,apache,tomcat配置https的阿里提供的文档