1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 函数指针和函数对象

函数指针和函数对象

时间:2020-04-14 08:29:54

相关推荐

函数指针和函数对象

1 函数指针

指向函数地址的指针变量,声明方式如下:

一般函数:void func(void);

指向函数func(void)的指针:void (*pfunc)(void) = func;

其中(*func)必须带有括号,否则编译器会认为是返回类型为void*的func(void)函数。

1 #include <iostream> 2 using namespace std; 3 4 int array[10]; 5 6 // 1 定义数组类型 7 typedef int (ArrayType)[10]; 8 9 // 2 定义一个数组指针类型10 typedef int (*pArrayType)[10]; // 注意指针的步长11 12 // 3 函数指针13 int func(int a)14 {15cout << "传入的值为:" << a << endl;16return a;17 }18 19 // 3.1 定义函数类型20 typedef int (funcType)(int);21 // 3.2 直接定义函数指针22 int (*pfunc)(int) = func;23 // 3.3 定义一个指向函数类型的指针类型24 typedef int (*PF)(int);25 26 // 3.4 函数指针做函数参数时,被调函数通过这个指针调用外部函数,从而形成回调27 int libfun(int (*pff)(int a))28 {29int x;30x = 10000;31pff(x);32 }33 34 int main()35 {36cout << "hello, func pointer..." << endl;37// 138ArrayType array; // 相当于int array[10];39array[0] = 1;40// 241pArrayType p;42p = &array; // 也可以直接定义:int (*p)[10] = &array;43(*p)[1] = 2;44 45// 3.1 用函数类型定义一个指向函数的指针46funcType* fp = NULL;47fp = func; // 函数名称代表函数的入口地址( 注意:func==&.&.(&func)==*.*.(*func) )48// 通过函数指针调用函数49fp(5);50 51// 3.252pfunc(10);53 54// 3.355PF pf = func;56(*pf)(15);57 58// 3.459int (*pff)(int a) = func;60libfun(pff);61 62return 0;63 }

2 函数对象

首先需要明确函数对象是一个对象,也就是一个类的实例,只不过这个对象具有某个函数的功能。具体实现时,只需要重载这个对象的()操作符即可:

1 #include <iostream> 2 using namespace std; 3 4 class Demo 5 { 6 public: 7intoperator()(int x){ return x; } 8 }; 9 10 int main()11 {12Demo d;13cout <<d(100)<< endl;14 15return 0;16 }

C++中的函数对象可以类比于C中的函数指针,一般而言,C中用函数指针的地方,在C++中就可以用函数对象来代替:

#include <iostream>using namespace std;class Demo{public:int operator()(int x){ return x; }public:template<typename T>T operator()(T t1, T t2){cout << t1 << " + " << t2 << " = " << t1 + t2 << endl;return t1 + t2;}};template<typename T>T addT(T t1, T t2, Demo& dd) /* 函数对象作为函数参数传递 */{return dd(t1, t2);}int main(){Demo d;cout << d(100) << endl;Demo dd; /* 定义函数对象 */addT(100, 200, dd); /* 函数对象的使用 */addT(100.5, 200.7, dd);return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。