数组(本内容摘录自《C++ Primer 第五版》P205)
typedef int arrt[10]; //arrt是一个类型别名,
//它表示的类型是含有10个整数的数组
using arrt=int[10]; //arrt的等价声明
arrt* func(int i); //func返回一个指向含有10个整数的数组的指针
函数指针形参(本内容摘录自《C++ Primer 第五版》P222)
/*
*显式地将形参定义成指向函数的指针
*/
void useBigger(const string &s1, const string &s2,
bool (*pf)(const string &,const string &));
bool lengthCompare(const string &, const string &);
正如useBigger的声明语句所示,直接使用函数指针类型作形参显得冗长而烦琐。类型别名和decltype能让我们简化使用了函数指针的代码:
//Func和Func2是函数类型
typedef bool Func(const string &, const string &);
typedef decltype(lengthCompare) Func2; //等价的类型
//FuncP和FuncP2是指向函数的指针
typedef bool(*Funcp)(const string &, const string &);
typedef decltype(lengthCompare) *FuncP2; //等价的类型
我们使用typedef定义自己的类型。Func和Func2是函数类型,而FuncP和FuncP2是指针类型。需要注意的是,decltype返回函数类型,此时不会将函数类型自动转换成指针类型。因为decltype的结果是函数类型,所以只有在结果前面加上*才能得到指针。可以使用如下的形式重新声明useBigger:
//useBigger的等价声明,其中使用了类型别名
void useBigger(const string &, const string &, Func);
void useBigger(const string &, const string &, FuncP2);
这两个声明语句声明的是同一个函数,在第一条语句中,编译器自动地将Func表示的函数类型转换成指针。
返回指向函数的指针
和数组类似,虽然不能返回一个函数,但是能返回指向函数类型的指针。然而,我们必须把返回类型写成指针形式,编译器不会将函数返回类型当成对应的指针类型处理。与往常一样,要想声明一个返回函数指针的函数,最简单的办法是使用类型别名:
using F = int(int*, int); //F是返回类型,不是指针
using PF = int(*)(int*, int); //PF是指针类型
其中我们使用类型别名将F定义成函数类型,将PF定义成指向函数类型的指针。必须时刻注意的是,和函数类型的形参不一样,返回类型不会自动地转换成指针。我们必须显式地将返回类型指定为指针:
PF f1(int); //正确:PF是指向函数的指针,f1返回指向函数的指针
F f1(int); //错误:F是函数类型,f1不能返回一个函数
F *f1(int); //正确:显式地指定返回类型是指向函数的指针