返回函数指针。

来源:互联网 发布:2017淘宝首页改版 编辑:程序博客网 时间:2024/06/05 02:44

 

来自:http://hi.baidu.com/girlkoo/blog/item/0addda0395a6fe084bfb515b.html

感谢原作者!!

/******************************************************************************************************************************/

这个朋友告诉我了两个问题,一是程序语句要简短明了,能让以后的人的很容的接手这个问题,这是程序员在软件开发过程重要注意的;二就是这个问题的理解,先定义一个这种指针类型,然后用这种指针类型定义函数,作为函数的返回值,函数体重的return语句返回的是一符合这一指针类型的函数。我自己编译了一个程序,成功了!下面是我实验的例子

int fun(const double a,const vector<string> &b,const int c)
{
cout<<a<<" "<<c<<endl;
for(vector<string>::const_iterator i=b.begin();i!=b.end();++i)
{
   cout<<*i;
}
return 0;
}
typedef int(*ff)(const double a,const vector<string> &b,const int c);
ff func()
{
return fun;
}

int main()
{
vector<string> ch;
ch.push_back("abc");
int num=5;
typedef int (*npoint)(const double,const vector<string> &,const int);
npoint ptr=func();
ptr(1.7,ch,num);
return 0;
}

/*************************************************************************************************************/

问题是解决了,但是这一用法在软件开发中有什么作用呢?我向我们学习过程中是需要学会一种用法,更要知道怎么去用,正好,在这里留言的这位朋友解决了这个问题:

int add(int,int);
int sub(int,int);
typedef int (*)(int,int) A;
A AddOrSub(char oper)
{
if(oper == '+')
return add;
else
return sub;
}
总结一下,这一用法可以在某些判断条件下返回特定的函数指针以调用特定的函数,个人觉得这有点像设计模式中的简单工厂模式,不知道对不对,如果有精通设计模式的朋友可以指点一下,谢谢了

原创粉丝点击