如下,利用定义的函数指针,以及递归实现 n+(n-1)+…..+1的求和运算。static 用于FunPr前面,程序刚开始运行时就完成初始化,也是唯一的一次初始化,其实是不会执行,隐藏了。最后调用的sumLast函数,是在n 为0,传入f(n-1),即是个溢出的数4294967295,因为unsigned int为双字节。
#include<iostream>
using namespace std;
typedef unsigned int (*FunPr) (unsigned int);
// ultimate return
unsigned int SumLast(unsigned int n)
{
return 0;
}
/**
* function calculate n+(n-1)+..+1+0
* @ parameter n
* @ return sum from 0 to n
*/
unsigned int SumFlow(unsigned int n)
{
static FunPr f[2]={SumLast, SumFlow};
return n+f[!!n](n-1);
}
void main()
{
int Num = 100;
cout<<"The sum is:"<<SumFlow(Num)<<endl;
}
源码download
https://github.com/codeAPmind/const-value/blob/master/function%20pointer/functionpointer.cc
Reference:
①http://wenku.baidu.com/link?url=pV0Wle1-LGxU_Yyjgamy2RZk20y6-ufXSwDYSslrgDm0SnIYWQ8kfGlIeKYnc1Zb7TUypsTjn9I9HB2QGT6q0mlgn8WsdkAgUu54jIEPtgy