理解仿函数

1、考虑下面的需求,vector中放置Person,Person有age和name字段。在vector中查找第一个Person c,这个很简单,方法如下:

  vector<Person>::iterator iter = find(personVector.begin(),personVector.end(),c);

  注意:find算法使用操作符==,比较对象是否相等,需要提供==重载。

2、考虑下面的需求,在vector中查找第一个age>15的Person。使用find_if和仿函数。如下:

  iter = find_if(personVector.begin(),personVector.end(),GetBigAgeFunctor(15));

3、完整代码如下:

Person.h

 1 #ifndef PERSON_H__
 2 #define PERSON_H__
 3 
 4 #include <string>
 5 #include <iostream>
 6 using namespace std;
 7 
 8 class Person
 9 {
10 private :
11     int age;
12     string name;
13 
14 public :
15     Person();
16 
17     Person(const int& age,const string& name);
18 
19     int GetAge() const;
20 
21     void SetAge(const int& age);
22 
23     string GetName() const;
24 
25     void SetName(const string& name);
26 
27     bool operator==(const Person& rhs);
28 
29     operator int() const;
30 
31 };
32 #endif
View Code

Person.cpp

 1 #include <string>
 2 #include "stdafx.h"
 3 
 4 Person::Person()
 5 {    
 6 }
 7 
 8 Person::Person(const int& age,const string& name):age(age),name(name)
 9 {
10 }
11 
12 int Person::GetAge() const
13 {
14     return this->age;
15 }
16 
17 void Person::SetAge(const int& age)
18 {
19     this->age = age;
20 }
21 
22 string Person::GetName() const
23 {
24     return this->name;
25 }
26 
27 void Person::SetName(const string& name)
28 {
29     this->name = name;
30 }
31 
32 bool Person::operator==(const Person& rhs)
33 {
34     return this->name == rhs.GetName() && this->age == rhs.GetAge();
35 }
36 
37 Person::operator int() const
38 {
39     return this->age;
40 }
View Code

main.cpp

 1 class GetBigAgeFunctor
 2 {
 3 private:
 4     int age;    
 5 
 6 public:
 7     GetBigAgeFunctor(const int& age):age(age)
 8     {
 9     }
10 
11     bool operator()(const Person& person)
12     {
13         return person>age;
14     }
15 };
16 
17 
18 int _tmain(int argc, _TCHAR* argv[])
19 {
20     Person a(13,"Andy");
21     Person b(8,"Bill");
22     Person c(27,"Caroline");
23     Person d(3,"David");
24 
25     vector<Person> personVector;
26     personVector.push_back(d);
27     personVector.push_back(a);
28     personVector.push_back(c);
29     personVector.push_back(b);
30 
31     vector<Person>::iterator iter = find(personVector.begin(),personVector.end(),c);
32 
33     iter = find_if(personVector.begin(),personVector.end(),GetBigAgeFunctor(15));
34 
35 }
View Code

4、操作符重载分为普通操作符和成员操作符,相对于普通操作符,成员操作符少了一个左操作数,成员操作符的左操作数就是成员方法中的this。
5、操作符重载,仿函数,隐式类型转换操作符分别为:  

  bool operator==(const Person& rhs)   操作符重载,可以认为operator== 就是方法名。

  bool operator()(const Person& person) 仿函数可以认为是一种特殊的操作符重载,也就是重载了操作符()

  operator int() const; 隐式类型转换操作符,可以认为没有形参,没有返回类型(类似构造方法),好像是重载了int  

  注意:一般情况下,不要使用隐式类型转换(构造方法加上explicit),也不要提供隐式类型转换操作符(可以提供AsXXX方法),因为他们实现了不合理的需求。

原文地址:https://www.cnblogs.com/nzbbody/p/3468141.html