函数对象,即一个重载了括号操作符“()”的对象。当用该对象调用此操作符时,其表现形式如同普通函数调用一般,因此取名叫函数对象。即重载函数调用操作符的类,其对象通常称为函数对象。函数对象使用重载()时,行为类似函数调用,因此也叫仿函数。
函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值。
#include<iostream>
using namespace std;
struct Add {
int operator()(int v1, int v2) {
return v1 + v2;
}
};
void test() {
Add add;
cout<<add(10, 20)<<endl;
}
int main() {
test();
return 0;
}
函数对象超出普通函数的概念,可以有自己的状态。
#include<iostream>
#include <string>
using namespace std;
struct Print {
Print() {
this->count = 0;
}
void operator()(string demo) {
cout << demo << endl;
this->count++;
}
int count;
};
void test() {
Print p;
p("This is a demo.");
p("This is a demo.");
p("This is a demo.");
p("This is a demo.");
p("This is a demo.");
cout << "Print打印输出的次数:" << p.count << endl; // 输出次数为5
}
int main() {
test();
return 0;
}
函数对象可以使用 new 创建对象:
#include<iostream>
#include <string>
using namespace std;
struct Print {
Print() {
this->count = 0;
}
void operator()(string demo) {
cout << demo << endl;
this->count++;
}
int count;
};
void test() {
auto *p = new Print();
(*p)("This is a demo.");
(*p)("This is a demo.");
(*p)("This is a demo.");
(*p)("This is a demo.");
cout << "Print打印输出的次数:" << p->count << endl;
delete p;
p = nullptr;
}
int main() {
test();
return 0;
}
函数对象可以作为参数进行传递。
#include<iostream>
#include <string>
using namespace std;
struct Print {
Print() {
this->count = 0;
}
void operator()(string demo) {
cout << demo << endl;
this->count++;
}
int count;
};
void do_print(Print &p, string s){
p(s);
}
void test() {
auto *p = new Print();
do_print((*p),"This is a demo.");
delete p;
p = nullptr;
}
int main() {
test();
return 0;
}