函数指针的几种用法

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/02 03:03:50
函数指针的几种用法

函数指针的几种用法
函数指针的几种用法

函数指针的几种用法
什么是函数指针?函数指针指向的是特殊的数据类型,函数的类型是由其返回的数据类型和其参数列表共同决定的,而函数的名称则不是其类型的一部分. 用typedef定义函数指针类型// 定义函数指针类型cmpFuntypedefint (*cmpFun)(constint&, constint&); (3)这样,cmpFun就成了一种数据类型,可以用它来声明和定义形如(1)式中的pf那样的函数指针,比如:cmpFun pf = 0;cmpFun pf = someFunction; 举个例子来说明一下:#include#includeusingnamespace std; // 定义函数指针pfint (*pf)(constint&, constint&); // 定义函数指针类型cmpFuntypedefint (*cmpFun)(constint&, constint&); // 具体函数int intCompare(constint& aInt, constint& bInt){ if(aInt == bInt) return 0; if(aInt > bInt) { return 1; } else { return -1; }} int main(void){ int aInt = 1; int bInt = 2; pf = intCompare; // pf = &stringCompare; // 和上面一句是完全一样的 // 使用pf if(pf(aInt, bInt) == 0) { cout