1. 定义
如果类定义了调用运算符(重载了函数调用运算符),则该类的对象被称作函数对象(function object),可以像使用函数一样使用该类的对象,
eg.
struct absInt{
int operator()(int val) const{
return val < 0 ? -val : val;
}
};
int i = -42;
absInt absObj;
int ui = absObj(i); //i被传递给absObj.operator()
2. 特性
- 函数调用运算符必须定义为成员函数。
- . 一个类可以定义多个不同版本的调用运算符,相互之间必须在参数数量或类型上有所区别。
- . 具备函数调用运算符的类同时也能存储状态,所以与普通函数相比它们更加灵活。
- . 函数对象常常作为泛型算法的实参。
class PrintString
{
public:
PrintString(ostream &o = cout, char c = ' '):
os(o), sep(c) {
}
void operator()(const string &s) const
{
os << s << sep;
}
private:
ostream &os; // stream on which to write
char sep; // character to print after each output
};
string strText = "test";
PrintString printer; // uses the defaults; prints to cout
printer(strText); // prints s followed by a space on cout
PrintString printer2(cerr, '_');
printer2(strText); //cerr中打印s,后面跟一个换行符
//函数对象常常作为泛型算法的实参
std::vector<string> vecStr = {
"a1", "b1"};
for_each(vecStr.begin(), vecStr.end(), PrintString(cerr, '-'));
输出结果:
test test_a1-b1-
【引用】