C++指向函数的指针

直接上代码:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

typedef int(*PF)(int *, int);
typedef bool (*cmpFcn)(const string&, const string&);
bool lenthCompare(const string& s1, const string& s2)
{
    return s1.size() == s2.size();
}

string::size_type sumLength(const string& s1, const string& s2)
{
    return s1.size() + s2.size();
}

bool cstringComare(char *s1, char* s2)
{
    return strlen(s1) + strlen(s2);
}
//第三个参数是一个函数指针
void useBigger(const string& s1, 
               const string& s2, 
               bool(*pf)(const string&, const string&))
{
    cout << pf(s1, s2) << endl;
}

int demo(int *p, int a)
{
    return 12;
}
//函数的指针也可以作为函数的返回结果:
//ff是一个函数,有一个形参x,返回结果是一个函数指针,返回的函数指针指向这样一个类型:int(*)(int *,int)
//int (*ff(int x))(int*, int)
//上一句简写为下面这一句:
PF ff(int x)
{
    cout << x << endl;
    return demo;
}

void ff(vector<double>vec)
{
    cout << "ff(vector<double>vec)" << endl;
}

void ff(unsigned int x)
{
    cout << "ff(unsigned int x)" << endl;
}

int main()
{
    //pf5是一个指针,它指向具有一个形参函数
    //void(*pf5)(int) = &ff;//指向的重载函数里面,必须有一个是精确匹配
    //double(*pf6)(vector<double>) = &ff;//指向的重载函数里面,必须有一个是精确匹配!所以这样的也不行
    void(*pf8)(unsigned int y) = &ff;//可以
    void(*pf7)(vector<double>) = &ff;//可以
    
    int a = 5;
    int* pa;
    /*
    cmpFcn pf4 = lenthCompare;
    useBigger("Hi", "function", pf4);
    getchar();
    return 0;
    */
    //直接传函数的名称:
    useBigger("Hi", "function", lenthCompare);
    cout << ff(2)(&a,a) << endl;
    getchar();
    return 0;
    //pf是一个指针,指向函数的指针
    //pf是一个局部变量
    //bool(*pf)(const string&, const string&);
    //bool(*pf2)(const string&, const string&);
    //bool(*pf3)(const string&, const string&);
    cmpFcn pf;
    cmpFcn pf2=0;
    cmpFcn pf3=0;
    pa = &a;
    //pf = &lenthCompare;//把函数的地址付给指针pf
    pf = lenthCompare;//上一句可以这样简写
    pf2 = lenthCompare;
    pf3 = pf2;//用一个指针赋值给另外一个指针
    //pf3 = sumLength;//不可以,不同的函数类型!
    //pf3 = cstringComare;//不可以,不同的函数类型!
    //cout << lenthCompare("hello", "wdddorld") << endl;
    cout<<(*pf)("hello", "worlddd") << endl;
    cout << pf2("hello", "worlddd") << endl;
    
    useBigger("hi", "function", lenthCompare);

    cout << *pa << endl;
    system("pause");
    return 0;
}
View Code

 

本例来自:https://www.bilibili.com/video/av37315901?from=search&seid=11705131729614210830

 

转载于:https://www.cnblogs.com/yibeimingyue/p/10511320.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值