函数运算符()重载
函数运算符()也能重载,它使得对象看上去像是一个函数名
ReturnType operator() (Parameters)
{
……
}
ClassName Obj;
Obj(real_parameters);
//->obj.operator() (real_parameters);
#include <iostream>
using namespace std;class Test
{
public:
int operator() (int a, int b)
{
cout << "operator() called." << a << " " << b << endl;
return a + b;
}
};int main()
{
Test sum;
int s = sum(, );//sum对象看上去像是一个函数,故也成为“函数对象”
cout << "a + b = " << s << endl;
return ;
}
#include <iostream>
using namespace std;class Less
{
int thres_;
public:
Less(int th) :thres_(th) {}
bool operator() (int);
};bool Less::operator() (int value)
{
return (value < thres_);
}void Filter(int *array, int num, Less fn)
{
for (int i = ; i < num; i++)
{
if (fn(array[i]))
cout << array[i] << " ";
}
cout << endl;
}int main()
{
int array[] = { ,-,,,- };
int thres;
cout << "thres:";
cin >> thres;
Less less_than(thres);
Filter(array, , less_than);
return ;
}