这个问题首先要搞清楚数组引用(指针)或者引用(指针)数组的区别:
int (&vp)[10]; //vp是一个含有10个整数的数组的引用
int &pv[10]; //pv是一个含有10个整数引用的数组
定义返回数组引用(指针)的函数实现如下:
/*定义函数返回string数组引用*/
#include <iostream>
#include <string>
std::string str[2] = {
"test",
"hello",
};
/*普通式*/
std::string (&func(std::string (&str)[2]))[2]
{
str[0] = "common";
return str;
}
/*typedef别名式*/
typedef std::string STR2[2];
STR2& func1(std::string (&str)[2])
{
str[0] = "typedef";
return str;
}
/* 尾置返回类型
* use c++11
*/
auto func2(std::string (&str)[2]) -> std::string (&)[2]
{
str[0] = "auto";
return str;
}
/* 类型推到式
* use c++11
*/
decltype(str)& func3(std::string (&str)[2])
{
str[0] = "decltype";
return str;
}
int main()
{
func(str);
std::cout << str[0] << std::endl;
std::cout << str[1] << std::endl;
func1(str);
std::cout << str[0] << std::endl;
std::cout << str[1] << std::endl;
func2(str);
std::cout << str[0] << std::endl;
std::cout << str[1] << std::endl;
func3(str);
std::cout << str[0] << std::endl;
std::cout << str[1] << std::endl;
return 0;
}
注意形参类型和函数返回类型都是数组的引用
以上指针同理。
运行结果:
$ g++ -std=c++0x -Wall func_ret.cpp
$ ./a.out
common
hello
typedef
hello
auto
hello
decltype
hello
总结有4种方式实现返回数组引用(指针)的函数:
普通式
typedef式
尾置返回类型
类型推导式
那么如何定义返回引用(指针)数组的函数呢?
很明显c++函数不能返回多个值(引用或指针),可以使用c++11新的标准规定,返回initializer_list,或者通过形参返回。