数组不能被拷贝, 所以返回值不能是数组类型.
但是我们可以使用返回指针的方式来实现返回数组的目的
声明一个返回数组指针的函数
- int (*fun(int i))[10];
- // func(int i) 表示调用 func 函数时需要一个 int 类型的实参
- // (*func(int i)) 意味着我们可以对函数调用的结果执行解引用操作
- // (*func(int i))[10] 表示解引用 func 的返回值将得到大小是 10 的数组
- // int (*func(int i))[10] 表示数组中的元素是 int 类型
返回值是 int 类型的数组的指针, 数组的大小是 10
使用尾置返回值类型 C++11
对复杂的返回值类型比较有用.
开头 auto 的意义就在于表示该函数应该有一个后置返回值类型
auto func(int i) -> int(*)[10];
使用 decltype
- int odd[] = {1,3,5,7,9};
- int even[] = {0,2,4,6,8};
- decltype(odd) *arrPtr(int i)
- {
- return (i % 2) ? &odd : &even;
- }
decltype 的含义就在于反解出表达式的类型, 并将之作为一个类型声明来使用
来源: https://www.cnblogs.com/ChattyKu/p/9602644.html