C/C++常见函数指针的用法
一、函数指针的写法
1 2 | void (*pFunc)( int ) 返回值类型 + (指针变量名)(形参列表) |
二、函数指针的定义方式
1.先定义函数的原型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <stdio.h> #include <stdlib.h> #include <string.h> //先定义出函数的类型,再通过类型定义函数指针变量 //定义一个函数类型,返回值是void,形参列表(int, int); typedef void (FUNC_TYPE)( int , int ); void func( int a, int b) { printf ( "a + b = %d\n" , a + b); } int main() { FUNC_TYPE *pFunc = func; pFunc(10, 20); return 1; } |
2.先定义函数指针的类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <stdio.h> #include <stdlib.h> #include <string.h> //先定义出函数指针的类型,再通过类型定义函数指针变量 //定义一个函数类型,返回值是void,形参列表(int, int); typedef void (*FUNC_TYPE)( int , int ); void func( int a, int b) { printf ( "a + b = %d\n" , a + b); } int main() { FUNC_TYPE pFunc = func; pFunc(10, 20); return 1; } |
3.直接定义函数指针
1 2 3 4 5 6 7 | int main() { //直接定义函数指针变量 void (*p)( int , int ) = func; p(10, 20); return 1; } |
4.定义函数指针数组
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 32 33 34 35 | #include <stdio.h> #include <stdlib.h> #include <string.h> //函数指针数组 void func1() { printf ( "func1\n" ); } void func2() { printf ( "func2\n" ); } void func3() { printf ( "func3\n" ); } void func4() { printf ( "func4\n" ); } int main() { //函数指针数组定义方式 void (*func_array[4])(); func_array[0] = func1; func_array[1] = func2; func_array[2] = func3; func_array[3] = func4; for ( size_t i = 0; i < 4; i++) { func_array[i](); } return 1; } |
三、在C++中使用函数指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> typedef int (*PTRUN)( int , int ); class MyTest { public : MyTest() {}; ~MyTest() {}; public : static int Add( int a, int b); }; int MyTest::Add( int a, int b) { return (a + b); } int main() { PTRUN pFun = MyTest::Add; std::cout << (*pFun)(3, 2) << std::endl; return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?