在了解重载()之前,首先要理解C++里面的函数对象的概念。
A FunctionObject type is the type of an object that can be used on the left of the function call operator.
即:函数对象类型是可以在函数调用操作符(PS:就是小括号())左侧使用的对象类型。
根据文档可以总结出函数对象的几种类型:
Notes
Functions and references to functions are not function object
types, but can be used where function object types are expected due to
function-to-pointer implicit conversion.Standard library
All pointers to functions satisfy this requirement.
All function objects defined in < functional >
Some return types of functions of < functional >
此外还有:
5. lambda表达式(C++11之后)
6. 重载了函数调用运算符()的类的对象
在C++中,自定义的比较函数中:常见的传入函数名,less或者greater对象都属于这种函数对象。但是,类似下面这种是做了隐式类型转换的。(具体转换流程没去看,有清楚的可以留言哈)
// 传入函数名
vector vec;
bool cmp(const pair& A. const pair& B) {return A.second < B.second;
}
sort(vec.begin(), vec.end(), cmp);
下面是其他对于函数对象的几种用法的实例(函数指针,重载了函数调用运算符()的类的对象
,lambda表达式)
#include void foo(int x) { std::cout << "foo(" << x << ")\n"; }int main()
{void(*fp)(int) = foo;fp(1); // calls foo using the pointer to functionstruct S {void operator()(int x) const { std::cout << "S::operator(" << x << ")\n"; }} s;s(2); // calls s.operator()s.operator()(3); // the sameauto lam = [](int x) { std::cout << "lambda(" << x << ")\n"; };lam(4); // calls the lambdalam.operator()(5); // the same
}
小括号是函数调用运算符。
重载()小括号,也就是重载函数调用运算符。
当用户定义类重载函数调用operator()时,它将成为FunctionObject类型。而FunctionObject类型可以当作一个函数一样来调用,这种类型的对象可以在函数调用表达式中使用:
这样说可能较为晦涩,但是下面的实例应该很好看懂:
// An object of this type represents a linear function of one variable a * x + b.
struct Linear
{double a, b;double operator()(double x) const{return a * x + b;}
};int main()
{Linear f{2, 1}; // Represents function 2x + 1.Linear g{-1, 0}; // Represents function -x.// f and g are objects that can be used like a function.double f_0 = f(0);double f_1 = f(1);double g_0 = g(0);
}
重载函数调用运算符()之后的类就是函数对象(FunctionObject)类,就有了函数对象(FunctionObject)类的功能,其实例化的对象,就是本文第一节所介绍的。