先看下面代码:
class StringSort
{
public:
bool operator() (const string &str1, const string &str2) const
{
return str1 > str2;
}
};
看的云里雾里。
没关系,我们先理解下面的代码:
class StringSort
{
public:
bool sort (const string &str1, const string &str2) const
{
return str1 > str2;
}
};
是不是很简单,就是把 sort 重载而已。
如何调用?创建一个对象 stringSort,调用 stringSort.sort(s1, s2)。注意不能用类直接调用,函数不是静态的。
可以类比 operator(),用 stringSort.operator(s1, s2) 调用。
由于 operator 是为了强调这是个运算符重载,因此可以简写成 stringSort(s1, s2)。这种写法是不是和构造函数相似?但他们区别大着呢。这种重载 () 是通过对象调用,只是对象的一个函数而已;而构造函数是通过类调用,进而生成一个新对象。可通过以下代码加深理解:
#include <iostream>
using namespace std;
class Clastype
{
public:
Clastype(int a)
{
cout << "Hello Clastype!" << a << endl;
}
bool operator ()(int b)
{
cout << "Hello Clastype()!" << b << endl;
return true;
}
};
int main()
{
Clastype a(1);
Clastype(2);
Clastype t = Clastype(3);
t(4);
Clastype *b = new Clastype(5);
(*b)(6);
}
结果为:
Hello Clastype!1
Hello Clastype!2
Hello Clastype!3
Hello Clastype()!4
Hello Clastype!5
Hello Clastype()!6
重载 () 作用:
对象的函数调用更方便。还有呢?这里就引出了函数对象的概念及作用。
函数对象:即一个重载了括号操作符“()”的对象(也就是上面的 stringSort)。当用该对象调用此操作符时,其表现形式如同普通函数调用一般,(stringSort 调用 () 函数的写法:stringSort.operator(s1, s2) 或 stringSort(s1, s2),后者 stringSort 看起来就像是一个函数)因此取名叫函数对象。
接着转到 函数对象 以继续了解。