指向函数的指针

来源:互联网 发布:零基础编程入门 编辑:程序博客网 时间:2024/06/10 20:43
#include <iostream>#include <string>#include <vector>using namespace std;typedef bool (*cmpFcn) (const string&, const string&);// typedef简化指针的定义,bool lengthCompare(const string &s1, const string &s2){return s1.size() == s2.size();}void ff(vector<double> vec){cout << "ff(vector<double> vec)" << endl;}void ff(unsigned int x){cout << "ff(unsigned int x)" << endl;}int demo (int *p, int a){return 12;}int (*ff(int x))(int *, int)  //ff是一个函数,有一个形参x,返回结果是一个函数指针,int(*)(int *, int){cout << x << endl;return demo;}void useBigger(const string &s1, const string &s2, bool (*pf)(const string&, const string&)){cout << pf(s1,s2) << endl;}int main (){bool (*pf)(const string &, const string &); // pf是一个指针,指向函数的指针:函数类型,void (*pf7)(vector<double>) = &ff;cmpFcn pf4 = lengthCompare;useBigger("hi", "function", pf4);  // 函数的名称就是一个指针,int a = 5;int *pa;cout << ff(2)(&a, a) << endl;  // 一个输出是2,另一个输出是12,//pf 是一个局部变量,// bool (*pf2)(const string&, const string&); //bool (*pf3)(const string&, const string&); cmpFcn pf2;cmpFcn pf3 = 0;pf2 = lengthCompare;pf3 = lengthCompare;pf = &lengthCompare;cout << lengthCompare("hello", "pointer") << endl;  // 输出是0,cout << (*pf)("hello", "point") << endl;  // 输出是1,return 0;}

0 0
原创粉丝点击