函数指针与指针函数,之前总是分不清,今天就好好把它两认认清楚。
先从概念说起,简单是理解。
函数指针:是指针。一个指向某一个函数入口地址的指针。
指针函数:是函数。一个返回值是指针的函数。
记忆:
从语文的角度讲,这俩个概念的主语在后,定语在前。
函数指针的主语是指针,而函数是指针的定语
指针函数的主语是函数,指针是定语。
如何声明和定义:
声明一个函数指针分为两部:
1.先声明一个你想指向的函数的原型
returnValue FuncName(Arg1,Arg2.....);
例如:
double DoSomething(int nArg1,int nArg2);
2.把函数原型中的函数名换成(*pf_FuncName)
例如:
double (*pf_DoSomething)(int nArg1,int nArg2);
3.Over
现在我们就声明了一个指针pf_FuncName,它指向函数FuncName的函数入口地址
例如:
pf_DoSomething就是一个指针,而使用解除引用操作符*修饰它之后,它就是函数本身(*pf_DoSomething)就是函数本身
一个小例子:
//普通函数 int sum(int nNum1,int nNum2); int sum(int nNum1,int nNum2) { return nNum1+nNum2; }; //函数指针例子 int DoSum(int nNum1,int nNum2,int (*sum)(int a,int b)); int DoSum(int nNum1,int nNum2,int (*sum)(int a,int b)) { return (*sum)(nNum1,nNum2); }; //指针函数例子 int* newSum(int nNum1,int nNum2); int* newSum(int nNum1,int nNum2) { int* result = new int; (*result) = nNum1+nNum2; return result; }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World! "; int result = sum(1, 2); int doSumResult = DoSum(2,3,sum); std::cout << "result:" <<result <<endl; std::cout << "doSumResult:" <<doSumResult <<endl; int* newResult = newSum(3, 4); std::cout << "newResult:" << (*newResult) <<endl; delete newResult; return 0; }
运行结果 :
Hello, World!
result:3
doSumResult:5
newResult:7