打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
函数指针总结_
2010-10-20 20:31
转载自 fredericky
最终编辑 fredericky
概念:函数指针是指指向函数而非指向对象的指针。

函数指针指向一个函数类型,函数类型由其返回类型以及形参表确定,与函数名无关:

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

pf points to function returning bool that takes two const string references.

1 用typedef简化函数指针的定义

eg:   typedef bool (*cmpFcn) (const string& ,const string&);

该定义表示cmpFcn是一种指向函数的指针类型的名字。该指针类型为“指向返回bool类型并带有两个const string引用形参的函数的指针”。以后使用这种函数指针类型时,只需直接使用cmpFcn即可。

2 指向函数的指针的初始化和赋值

在引用函数名但又没调用该函数时,函数名将被自动解释为指向函数的指针。假设有函数:

// compares lenghts of two strings
bool lengthCompare(const string& ,const string&);

除了用作函数调用的左操作数以外,对lengthCompare的任何使用都被解释为如下类型的指针:
bool (*) (const string& , const string&);

可以使用函数名对函数指针做初始化或赋值:

cmpFcn pf1 = 0;

cmpFcn pf2 = lengthCompare;

pf1 = lengthCompare;

pf2 = pf1;

此时,直接引用函数名等效于在函数名上应用取地址操作符:

cmpFcn pf1 = lengthCompare;

cmpFcn pf2 = &lengthCompare;

将函数指针初始化为0,表示该指针不指向任何函数。

3 通过指针调用函数

cmpFcn pf = lengthCompare;

lengthCompare("hi","bye");

pf("hi","bye");

(*pf) ("hi","bye");

4 函数指针形参

函数的形参可以是指向函数的指针。这种形参可以用以下两种形式编写:

// third parameter is a function type and is automatically treated as a pointer to function
void useBigger( const string&, const string&, bool (const string&, const string& ));

// equivalent declaration: explicitly define the parameter as a pointer to function
void useBigger(const string&, const string&, boo (*) (const string&,const string& ));

5 返回指向函数的指针
函数可以返回指向函数的指针,但是挺绕的:


int ( *ff(int) ) (int* , int);

ff(int) 将ff声明为一个函数,它带有一个int形参。该函数返回

int (*) (int* ,int);

它是一个指向函数的指针,所指向的函数返回int型并带有两个分别是int*型和int型的形参。

使用typedef可使该定义更简单易懂:

// PF is a pointer to a function returning an int , taking an int* and an int

typedef int (*PF) (int*,int);

PF ff(int);

允许将形参定义为函数类型,但函数的返回类型则必须是指向函数的指针,而不能是函数。

typedef int func(int*, int);

void f1(func); // ok : f1 has a parameter of function type

func f2(int); // error : f2 has a return type of function type

func *f3(int); // ok : f3 returns a pointer to function type



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
6.7
typedef用法详解
C++普通函数指针与成员函数指针实例解析
5分钟搞懂C 函数指针与函数类型
第一部分 基础语言之六函数
C语言中操作字符串的一些函数源代码
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服