[导入]返回指向函数的指针

C++ Primer 7.9节

-----------------------------------------------------------------------------------------------------------------------------------

函数可以返回指向函数的指针,但是,正确写出这种返回类型相当不容易:

// ff is a function taking an int and returning a function pointer

// the function pointed to returns an int and takes an int* and an int

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);

// ff returns a pointer to function

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

函数的指针,而不能是函数。

具有函数类型的形参所对应的实参将被自动转换为指向相应函数类型的指针。但是,当返回的
是函数时,同样的转换操作则无法实现:

// func is a function type, not a pointer to function!

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

------------------------------------------------------------------简单例子---------------------------------------------------------------------------------

#include<iostream>
using namespace std;

int (*ff(int f))(int val1,int val2);
int (*fun)(int val1,int val2);
int foo(int a,int b);

int main()
{
   fun=ff(0);
   cout<<fun(1,2)<<endl;
   return 0;
}

int foo(int a,int b)
{
   cout<<a<<" "<<b<<" foo is calling..."<<endl;
   return b+1;
}

int (*ff(int f))(int val1,int val2)
{
   cout<<f<<" ff is calling..."<<endl;
   return foo;
}

-------------------------------------------------------------------------------输出------------------------------------------------------------------------------

0 ff is calling...
1 2 foo is calling...
3

----------------------------------------------------------------------------使用typedef-----------------------------------------------------------------------

#include<iostream>
using namespace std;


typedef int (*fun)(int val1,int val2);
fun ff(int);
int foo(int a,int b);

int main()
{
   cout<<ff(0)(1,2)<<endl;
   return 0;
}

int foo(int a,int b)
{
    cout<<a<<" "<<b<<" foo is calling..."<<endl;
    return b+1;
}

fun ff(int f)
{
   cout<<f<<" ff is calling..."<<endl;
   return foo;
}

阅读全文
类别:c/c++ 查看评论
文章来源:http://hi.baidu.com/janqii/blog/item/32b06427b807893fc89559d7.html

posted on 2010-04-27 23:48 janqii 阅读(388) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿

随笔档案(15)

搜索

最新评论

阅读排行榜

评论排行榜