首页 > 其他 > 详细

libsvm代码阅读:关于函数指针

时间:2014-02-21 05:09:23      阅读:414      评论:0      收藏:0      [点我收藏+]

在libsvm中有如下代码:

static void print_string_stdout(const char *s)
{
	fputs(s,stdout);
	fflush(stdout);
}
static void (*svm_print_string) (const char *) = &print_string_stdout;
我在论坛中曾经发帖:

bubuko.com,布布扣

看了Pump天天学习同学的回复,我才回想起来:第六行那原来是个函数指针,平时没用到,就给忘了,只能拿出教材重新来学习一遍:

函数指针是指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关:

// pf points to function returning bool thar takes two const string references
bool (*pf) (const string &, const string &);
这个语句将pf声明为指向函数的指针,它所指向的函数带有两个const string &类型的形参和bool类型的返回值。

注意*pf两侧的圆括号是必需的,若没有,则就不是函数指针了。

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

typedef简化函数指针的定义

函数指针类型相当冗长。使用typedef为指针类型定义同义词,可将函数指针的使用大大简化

typedef bool (*cmpFn)(const string &, const string &)
该定义表示cmpFn是一种指向函数的指针类型的名字。该指针类型为:“指向返回bool类型并带有两个const string 引用形参的函数的指针”。在要使用这种函数指针类型时,只需直接使用cmpFn即可,不必每次都把整个函数类型声明全部写出来。


通过指针调用函数

指向函数的指针可用于调用它所指向的函数,可以不需要使用解引用操作符,直接通过指针调用函数:

bool lengthCmp(const string&, const string &);
cmpFn pf = lengthCmp;
lengthCmp=("hi","bye");//direct call
pf("hi","bye");//equivalent call: pf1 implicitly dereferenced
(*pf)("hi","bye");//equivalent call: pf1 explicitly dereferenced


ref:

《C++ Primer 4th》pp237-239


libsvm代码阅读:关于函数指针

原文:http://blog.csdn.net/linj_m/article/details/19542421

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!