Pointers to Function

来源:互联网 发布:郑州软件开发 编辑:程序博客网 时间:2024/05/21 21:34

Function type

A function type is determined by its return value and parameter list

Pointers to function

a pointer to funtion is a pointer points to a object of particular  function type

bool (*pf) (const string&, const string&);//definition

The parentheses is necessary

bool *pf(const string&, const string&);//declares a function named pf that returns a bool*

using typedefs to simplify function pointer definition

typedef bool (*cmp)(const string&,const string&);cmp pf1=0;//initialize a pointer with null

Initialization and Assignment

function name is implicit pointer of that function type

cmp pf1=lengthCompare;//equivalent to cmp pf1=&lengthCompare
(why?)

There is no conversion between one pointer to function type and another


Application of function pointer

1 calling a function through a function pointer

bool lengthCompare(const string& s1,const string& s2){return s1.size()==s2.size()? true : false ;}

typedef bool (*cmp)(const string&,const string&);cmp pf1=lengthCompare;//initialize a pointer with nullstring s1="abc";string s2="abcsfd";bool flag;flag=lengthCompare(s1,s2);//method 1flag=pf1(s1,s2);//equivalent to *pf1(s1,s2)

2 passing a function as parameter to another

bool isSameLength(const string& s1,const string& s2, bool(*f)(const string& ,const string&)){  if(f(s1,s2)) return true;  else return false;}

just a silly function

3 returning a pointer to function

example, a function returns a pointer to function type of int(int*,int)

int (*f(int))(int*,int);

for simplicity still typedef can be used

typedef int(*PF)(int*,int)//syntax for typedef int(*)(int*,int) PF

PF f(int)

the return type of a function can only be pointer to function,but not function type itself(why?)
typedef int func(int,int)//func is a function type,not a pointer to functionvoid f1(func);//the parameter convert automatically to func*func f2(int); //errorfunc *f3(int);//ok





原创粉丝点击