指针函数和函数指针
来源:互联网 发布:建筑电气数据手册 编辑:程序博客网 时间:2024/06/04 22:45
函数指针
函数指针:指向函数的指针变量,在C编译时,每一个函数都有一个入口地址,那么指向这个函数的函数指针便是指向这个地址。函数指针主要有两个作用:用作调用函数和做函数的参数。
int (*func)(int x);
诸如上面的代码这是申明了一个函数指针,代码(*func)中括号是必须的,这会告诉编译器这是一个函数指针而不是声明一个具有返回类型为指针的函数,后面的形参要是这个函数所指向的函数形参而定。使用如下面的代码:
#include <iostream>using namespace std;int(*func)(int a, int b);int bar(int a, int b){ return a + b;}int foo(int a, int b){ return a;}int _tmain(int argc, _TCHAR* argv[]){ func = bar; cout << func(12, 34) << endl; system("pause"); func = foo; cout << func(12, 34) << endl; system("pause"); return 0;}
这样的声明有些繁琐,其实可以使用typedef来进行简化:
#include <iostream>using namespace std;typedef int(*PF)(int, int);//int(*func)(int a, int b);int bar(int a, int b){ return a + b;}int foo(int a, int b){ return a;}int _tmain(int argc, _TCHAR* argv[]){ PF func; func = bar; cout << func(12, 34) << endl; system("pause"); func = foo; cout << func(12, 34) << endl; system("pause"); return 0;}
函数指针的另一个作用就是作为函数的参数,可以在一个函数的形参列表中传入函数指针,然后边可以在这个函数中使用这个函数指针所指向的函数,这样边可以使程序变得更加清晰和简洁。
#include <iostream>using namespace std;typedef int(*PF)(int, int);//int(*func)(int a, int b);int bar(int a, int b){ return a + b;}int foo(int a, int b){ return a;}void func(int a, int b, PF ptr){ cout << ptr(a, b) << endl; return;}int _tmain(int argc, _TCHAR* argv[]){ PF ptr; ptr = bar; func(12, 34, ptr); system("pause"); ptr = foo; func(12, 34, ptr); system("pause"); return 0;}
指针函数
与函数指针相区别的定义应该就是指针函数,指针函数本质上是一个函数,是指函数的返回值为指针的函数,一般是形如下的函数:
int* func(int x,int y);
0 0
- 指针函数和函数指针
- 函数指针和指针函数
- 指针函数和函数指针
- 指针函数和函数指针
- 函数指针和指针函数
- 函数指针和指针函数
- 函数指针和指针函数
- 指针函数和函数指针
- 函数指针和指针函数
- 指针函数和函数指针
- 函数指针和指针函数
- 指针函数和函数指针
- 指针函数和函数指针
- 指针函数和函数指针
- 函数指针和指针函数
- 函数指针和指针函数
- 函数指针和指针函数
- 函数指针和指针函数
- R packages
- python的__getattr__方法
- VirtualBOX 虚拟机安装 OS X 10.9 Mavericks 及 Xcode 5,本人X220亲测
- git常用命令
- .aspx页面在低版本ie下文档模式自动为“杂项(Quirks)”导致页面变样的问题
- 指针函数和函数指针
- VMware内存分配初探
- Sicily 11600. Pick It
- java读取 *.properties文件
- 动态分配二维数组
- css3中webkit-box的用法
- C++STL 常用 函数 用法
- 计算机中的数学
- Next Permutation