函数是这样一个Object:它定义了operator()操作。例如:
class FunctionObjectType {
public:
void operator() {
statements
}
}
这样的定义有三个重要的优点:
1. 如果它又一个状态它会更加智能,事实上你可以在同一个函数中有两个实例,这两个实例可以用同一个恶有多个状态的函数对表示。
2. 每个函数对象都用它自己的类型。
3. 一个函数对象比函数指针的效率高。
函数对象可以作为一个排序标准:
class Person {
public:
string firstname() const;
string lastname() const;
...
};
class PersonSortCriterion {
public:
bool operator() (const Person& p1, const Person& p2) const {
return p1.lastname()<p2.1astname() ||
(! (p2.1astname()<p1.lastname()) &&
p1.firstname()<p2.firstname());
}
};
typedef set<Person,PersonSortCriterion> PersonSet;
PersonSet coll;
当然也可以在Person类中自定义一个自己的<操作符,在Set中传递默认的排序标准就行了。
class FunctionObjectType {
public:
void operator() {
statements
}
}
这样的定义有三个重要的优点:
1. 如果它又一个状态它会更加智能,事实上你可以在同一个函数中有两个实例,这两个实例可以用同一个恶有多个状态的函数对表示。
2. 每个函数对象都用它自己的类型。
3. 一个函数对象比函数指针的效率高。
函数对象可以作为一个排序标准:
class Person {
public:
string firstname() const;
string lastname() const;
...
};
class PersonSortCriterion {
public:
bool operator() (const Person& p1, const Person& p2) const {
return p1.lastname()<p2.1astname() ||
(! (p2.1astname()<p1.lastname()) &&
p1.firstname()<p2.firstname());
}
};
typedef set<Person,PersonSortCriterion> PersonSet;
PersonSet coll;
当然也可以在Person类中自定义一个自己的<操作符,在Set中传递默认的排序标准就行了。