一、函数指针(通过参数与返回值来确定一个函数指针)
1、直接声明
int (*pf)(string& a,string & b); //定义pf指向参数为a,b,返回值为int类型的函数
int * pf(string&a,string &b); //括号必不可少,此时声明了一个pf函数,返回值为int *型指针
2、定义(定义函数指针必须与指向的函数参数、返回值类型相同)
intfunction(string &a,string &b); //定义例子函数
int(*pf)(string& a,string& b) = function;
int(*pf)(string& a,string& b) = &function; //写法等价
3、调用
int temp =pf("hello","bye");
int temp =(*pf)("hello","bye");
int temp =function("hello","bye"); //写法等价
4、函数指针也是指针
函数指针也是指针,不过不存在不同指针之间的类型转换
函数指针是一个4字节的变量,其存储的内容为函数执行地址
可以将函数指针指向nullptr(0x0000)保留地址无权操作
二、函数指针作为参数
1、函数和数组一样,不能作为参数,但是可以作为函数参数
2、声明
int temp(conststring &a,int (*pf)(string &a,string &b));
int temp(conststring &a,int pf(string &a,string &b)); //第二个参数胡自动的转换为函数指针
3、调用
intfunction(string &a,string &b); //函数声明
temp("hello",function); //自动将函数名转换为函数指针
temp("hello",&function)
4、利用类型别名来简化声明
intfunction(string &a,string &b); //函数声明
typedef intfunc(string &,string &);
typedefdecltype(function) func2; //等价都是函数类型
typedef int(*funcp)(string &,string &);
tydedefdecltype(function) funcp2; //等价都是函数指针类型
temp("hello",func); //自动转换为函数指针
temp("hello",funcp);
三、返回指向函数的指针
1、和数组类似,不能返回一个函数,但是能够返回一个函数指针
2、利用类型别名来返回函数指针
using pf = int(*)(string &,string &);
using f =int(string &,string &); //返回值不像形参,不能自动转换为函数指针
pftemp(int,int); //此函数的返回值为 pf函数指针类型
f * temp(int,int); //f返回值为函数指针类型
3、原始函数声明
int(*temp(string &,string &))(int,int);
函数temp接受双形参string,返回接受函数双形参int,返回值为int的函数指针
从外往内阅读吗,首先是内层括号,函数接收参数为string引用,往外,返回为指针,在往括号外,接收双int参数,返 回为int
所以该函数返回为接收双int参数返回值为int的函数指针。
4、使用尾置类型
auto temp(string&,string &) -> int(*)(int ,int);
5、使用decltype
function(int,int);
decltype(function) * temp(string &,string &);
四、声明类型别名的三种姿势
1、using
using f = int;
using p = int*;
using pp = int**;
using array =int [];
using array =int* [];
using arrayp =int (*)[];
using arrayp =int* (*)[];
using f = int&;
using array =int (&)[];
using array =int *(&)[];
using func =string& (int &,int &);
using funcp =string& (*)(int &,int &);
2、typedef
typedef int f;
typedef int * p;
typedef int **p;
typedef intarray[] ;
typedef int*array[];
typedef int*(*arrayp)[];
typedef int&f;
typedef int(&array)[]; //引用数组
typedef int*(&array)[];
typedefstring& temp(int&,int&) //函数
typedefstring& (*temp)(int&,int&)
3、decltype
decltype 是基于变量来计算类型的
const int temp;
decltype(temp)tempA;
int*(*temp)[10];
decltype(temp)tempA;
int* temp(string&a,string &b); //函数
decltype(temp)*a;
decltype(temp)*test(int a,int b); //函数返回函数指针
int*(*temp)(string &a,string &b);//函数指针指向双string&形参,返回值为int *的函数
decltype(temp)a;
decltype(temp)test(int a,int b); //函数返回值为函数指针