特点:
- 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
- 函数对象超出普通函数概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递
代码演示:
#include<iostream>using namespace std;#include<string>//函数对象(仿函数)//● 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值//● 函数对象超出普通函数概念,函数对象可以有自己的状态//● 函数对象可以作为参数传递//一:函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值class MyAdd {public:int operator()(int a, int b) {return a + b;}};void test01() {MyAdd myadd;cout << myadd(10, 5) << endl;}//二:函数对象超出普通函数概念,函数对象可以有自己的状态class MyPrint {public:MyPrint() {this->count = 0;}void operator()(string a) {cout << a << endl;this->count++;}int count;//记录函数调用次数};void test02() {MyPrint myprint;myprint("Hello World!");myprint("Hello World!");myprint("Hello World!");myprint("Hello World!");cout << "myprint的调用次数为:" << myprint.count << endl;}//三:函数对象可以作为参数传递void doPrint(MyPrint& mp, string a) {mp(a);}void test03() {MyPrint myprint;doPrint(myprint, "Hello C++");}int main() {test01();test02();test03();return 0;}
运行结果:
