随笔 - 1762  文章 - 0  评论 - 109  阅读 - 431万

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

 

posted on   一杯明月  阅读(193)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示