C++:数组的引用,作形参或是作返回类型,不用指针

一、数组的引用

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

形式:

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)[5])
{
    for (auto i : arr)
        cout << i << endl;
}

int main()
{ 
    int odd[5] = {1, 3, 5, 7, 9};
    print(odd);
    return 0;  
}

 

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

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

 

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

 

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

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

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

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

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

写法:

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

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

#include <iostream>
#include <vector>
#include <cctype>
#include <string>
#include <iterator>
#include <initializer_list>

using namespace std; 

int odd[] = {1, 3, 5, 7, 9};
int even[] = {0, 2, 4, 6, 8};

//int (&func(int i))[5]
//auto func(int i) -> int(&)[5]
decltype(odd) &func(int i)
{
    return (i % 2) ? odd : even;
} 
  
int main()
{ 
    cout << func(3)[1] << endl;            //输出3 
    return 0;  
}

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

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

助记:

int &func(int a, int b)
{
    return a > b ? a : b;
}  
//函数调用结束后,返回b的引用,返回引用的优点在于不用拷贝一个值返回 
  
int main()
{ 
    int x = 3, y = 4;
    int ans = func(x, y);    //ans = 4 
    return 0;  
}

 

posted @ 2019-07-17 10:46  龙雪  阅读(389)  评论(0编辑  收藏  举报