返回类型和return语句
返回数组指针:
声明一个返回数组指针的函数
Type (*function(parameter_list))[dimension]
其中type表示元素类型,dimension表示数组大小
以int (*func(int i))[10];为例
- func(int i)表示调用func函数时需要一个int类型的实参
- (*func(int i))意味着我们可以对函数调用的结果执行解引用操作
- (*func(int i))[10] 表示解引用func的调用将得到一个大小是10的数组
- int (*func(int i))[10] 表示数组中的元素是int类型
使用尾置返回类型
任何函数的定义都可以使用尾置返回。
//func接受一个int类型实参,返回一个指针,指向含有10个整数的数组
auto func(int i) -> int(*)[10]
使用decltype
如果已知函数返回的指针指向哪一个数组,就可以使用decltype声明返回类型。
int odd[] = {1,3,5,7,9};
int even[] = {0,2,4,6,8};
//返回一个指针,该指针指向含有5个整数的数组
dectype(odd) *arrPtr(int i)
{
return (i%2) ? &odd : &even;//返回一个指向数组的指针
}
注意decltype的结果是一个数组,要想表示arrPtr返回指针必须在函数声明时加一个*。
函数指针
函数指针指向的是函数,函数指针指向某种特定类型,该类型由它的返回类型和形参类型共同决定,与函数名无关。
扫描二维码关注公众号,回复:
9143522 查看本文章
bool lengthCompare(const string &,const string &);
声明一个指向该函数的指针,只需要用指针替换函数名即可。
//pf指向一个函数,该函数参数是两个const string的引用,返回值是bool类型
bool (*pf)(const string &,const string &);//未初始化
使用函数指针
当我们把函数名作为一个值使用时,该函数自动转换为指针
pf = lengthCompare;
pf = &lengthCompare;//等价:&是可选的
bool b1 = pf("hello","goodbye");//调用lengthCompare函数
bool b2 = (*pf)("hello","goodbye");//一个等价调用
重载函数的指针
使用重载函数时必须上下文清晰地界定到底选用哪个函数
void ff(int *);
void ff(unsigned int);
void (*pf1)(unsigned int) = ff; //pf1指向ff(unsigned int);
函数指针形参
函数的形参可以是指向函数的指针
//第三个类型是函数类型,它会自动转换为指向函数的指针
void useBigger(const string &s1,const string &s2,bool pf(const string&,const string&));
void useBigger(const string &s1,const string &s2,bool (*pf)(const string&,const string&));
//等价声明
返回指向函数的指针
可以返回指向函数类型的指针。
using F = int(int*,int); //F是函数类型,不是指针
using PF = int(*)(int*,int);//PF是指针类型
PF f1(int);//正确,PF是指向函数的指针,f1返回指向函数的指针
F f1(int);//错误,F是函数类型,f1不能返回一个函数
F *f1(int);//正确
//也可以直接声明
int (*f1(int))(int *,int);
//或者
auto f1(int) -> int (*)(int *,int)