C++学习记录-函数对象
一、函数对象
一个函数对象,即一个重载了括号运算符()的对象,也叫函数符。利用该对象调用()时和普通的函数调用一般,因此也叫仿函数
- 函数对象的本质是一个类,而不是一个函数,使用时应该实例化成一个对象
- 函数对象在使用时可以像普通函数一样调用,可以有参数,可以有返回值
- 函数对象可以有自己的状态
- 函数对象可以作为参数传递
二、示例:
1.函数对象在使用时可以像普通函数一样调用,可以有参数,可以有返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class line { public: double length; public: line(double a) :length(a) {} };
class forspace { public: double operator()(const line& a) { return a.length * a.length; } };
int main() { line l(10.0); forspace sp; cout << sp(l); }
|
2.函数对象可以有自己的状态
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class line { public: double length; public: line(double a) :length(a) {} };
class forspace { public: double operator()(const line& a) { usecount++; return a.length * a.length; }
public: int usecount=0; };
int main() { line l(10.0); forspace sp; cout << sp(l); cout << "调用的次数:" << sp.usecount; }
|
3.函数对象可以作为参数传递
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class mystring { public: void operator()(string name) { cout << name << endl; } };
void myprintf(mystring &mf,string name) { mf(name); }
void test3() { mystring mss; myprintf(mss,"hello C++"); }
|