本质是重载了调用运算符"()"的类,拥有函数的行为,但本质是一个类对象
2.作用:相比于普通的全局函数或函数指针,仿函数作为类即能实现函数的功能,也能通过类数据成员存储一些定义好的参数,在实现了代码复用的同时,可扩展性更强,维护性更好
3.举例:-
跟普通函数一样使用,实现一个比较器的功能
#includeusing namespace std; // 仿函数 class Func { public: Func() {} void operator()(int n) { cout << "仿函数输出:" << (n > 10 ? "大于" : "不大于") << endl; } }; // 普通函数 void compare(int n) { cout << "普通函数输出:" << (n > 10 ? "大于" : "不大于") << endl; } void test1(int n, void (*cfunc)(int)) { // 传入函数指针 cfunc(n); } void test2(int n, Func& fun) { // 传入仿函数类 fun(n); } int main() { int n = 20; test1(n, compare); Func func; test2(n, func); return 0; }
-
以上面为基础,假设现在要求多一个比较器的比较阈值参数,不能使用默认阈值,这时候仿函数的作用就体现出来了,只需要修改仿函数内容,而无须更改使用该类的函数,代码中1.1,1.2,1.3为普通函数的修改,2.1为仿函数的修改,显然仿函数的扩展性更强
#includeusing namespace std; // 2.1修改仿函数 class Func { public: Func() {} Func(const int& _data) :data(_data) {} void operator()(int n) { cout << "仿函数输出:" << (n > data ? "大于" : "不大于") << endl; } private: int data; }; // 1.1更改函数参数 void compare(int n, int thrd) { cout << "普通函数输出:" << (n > thrd ? "大于" : "不大于") << endl; } int thrd = 20; // 1.2设定全局变量 void test1(int n, void (*cfunc)(int,int)) { // 1.3更改传入指针参数 cfunc(n,thrd); } void test2(int n, Func& fun) { fun(n); } int main() { int n = 20; test1(n, compare); Func func(20); // 2.2有参构造 test2(n, func); return 0; }
-
构造成模板类,用于多种类型的对比,复用性更强
#includeusing namespace std; template class Func { public: Func(const T& _data) :data(_data) {} void operator()(T n) { cout << "仿函数输出:" << (n > data ? "大于" : "不大于") << endl; } private: T data; }; void test2(int n, Func & fun) { fun(n); } int main() { int n = 20; Func func(20); test2(n, func); return 0; }
做笔记使用,如果有写的不好的或者错误的,还请指正!!!谢谢!!溜了溜了~~~