当前位置: 首页 > news >正文

20250526-C++基础-函数指针

C++基础-函数指针

函数指针,顾名思义就是指向函数的指针,用一个变量来存储函数的地址,可以通过这个变量(指针)间接访问函数。(可以把函数指针名看作函数名来进行函数调用)。代码及说明如下:

#include <iostream>
#include<functional>using namespace std;class Test
{
public:int mul(int, int);
};int Test::mul(int a, int b) 
{return a * b;
}int add(int num1, int num2)
{int sum = num1 + num2;return  sum;
}int sub(int num1, int num2)
{return num1 - num2;
}int calc(int num1, int num2, int(*func)(int, int)) 
{return func(num1, num2);
}
int main()
{//1、获取函数地址与获取函数值cout << add << endl;    //00007FF7288B1465cout << sub << endl;   //00007FF7BDC51474cout << add(4, 5) << endl;  //9//2、使用函数指针//语法:返回类型 (*指针名称)(参数列表);cout << "*****************2" << endl;int (*fp1)(int, int) = add;cout << (*fp1)(2, 3) << endl;   //5cout << fp1(2, 3) << endl;  //5//3.使用typedef简化函数指针cout << "*****************3" << endl;typedef int(*Fp)(int, int);Fp fp2 = add;cout << fp2(6, 9) << endl;  //15//4.函数指针作为参数,将要执行的函数地址传过去cout << "*****************4" << endl;cout << calc(8, 2, add) << endl;    //10cout << calc(8, 2, sub) << endl;    //2//5.用functiona包装函数cout << "*****************5" << endl;function<int(int, int)> fp3 = add;cout << fp3(1, 2) << endl;  //3//6.数组函数指针cout << "*****************6" << endl;int(*fps[])(int, int) = { add, sub };for (auto fp : fps)cout << fp(4, 2) << endl;   //6   2function<int(int, int)> fps2[] = { add, sub };for (auto fp : fps2) cout << fp(2, 1) << endl;   //3     1//7.类的成员函数指针cout << "*****************7" << endl;int(Test:: * fp4)(int, int) = &Test::mul;Test test;cout << (test.*fp4)(3, 4) << endl;  //12}

输出结果:

00007FF701C9142E
00007FF701C910FA
9
*****************2
5
5
*****************3
15
*****************4
10
6
*****************5
3
*****************6
6
2
3
1
*****************7
12

在这里插入图片描述

http://www.xdnf.cn/news/660655.html

相关文章:

  • Pyhton_25_5_26
  • 中断和异常
  • 2025-05-26 什么是“AI 全栈”
  • K8s中间件Kafka上云部署
  • Treasures in Discarded Weights for LLM Quantization阅读
  • 华为OD机试_2025 B卷_欢乐的周末(Python,100分)(附详细解题思路)
  • Anaconda 在 Windows 上的安装教程
  • SpringBoot3集成Oauth2.1——7数据库存储用户信息
  • 基于DDD的企业团餐订餐平台微服务架构设计与实现(二)
  • GitLab 18.0 正式发布,15.0 将不再受技术支持,须升级【二】
  • sd webui 安装sd-webui-TemporalKit 加载报错解决办法
  • Java-ArrayList集合的遍历方式详解
  • uni-app学习笔记十五-vue3中defineExpose的使用
  • 如何用Python搭建一个网站
  • Qwen-Agent的使用示例-天气查询
  • Spring + MyBatis/MyBatis-Plus 分页方案(limit分页和游标分页)详解
  • 【排错】kylinLinx环境python读json文件报错UTF-8 BOM
  • WEB安全--RCE--webshell HIDS bypass3
  • try-with-resources
  • md650场景联动
  • 华为OD机试真题——考勤信息(2025A卷:100分)Java/python/JavaScript/C/C++/GO最佳实现
  • Go语言入门指南
  • lwip_bind、lwip_listen 是阻塞函数吗
  • 从实训到实战:家庭教育干预课程的产教融合定制方案
  • 1期临床试验中的联合i3+3设计
  • IndexTTS - B 站推出的文本转语音模型,支持拼音纠正汉字发音(附整合包)
  • 基于web的二手交易商城-设计
  • uniapp好不好
  • 攻防世界 unseping
  • 从0到1搭建AI绘画模型:Stable Diffusion微调全流程避坑指南