12.5.5 操作符->*和()的重载
在重载->*之前,要先重载()。()操作的类型是->*返回的类型。operator()用来建立所谓的函数对象(function object)。()必须作为成员函数来重载,且可以带任意数量的参数,下面是一个例子:
class LessThan {
public:
LessThan( int val ) : _val( val ){}
int comp_val() const { return _val; }
void comp_val( int nval ){ _val = nval; }
bool operator()( int value ) const;
private:
int _val;
};
inline bool
LessThan::operator()( int value ) const
{ return value < _val; }
int count_less_than( const vector<int> &vec, int comp )
{
LessThan lt( comp );
int count = 0;
for ( int ix = 0; ix < vec.size(); ++ix )
if ( lt( vec[ ix ] )) // lt(vec[ix])调用了被重载的函数
++count;
return count;
}
->*重载的例子
class Dog {
public:
int run(int i) const {
cout << "run\n";
return i;
}
int eat(int i) const {
cout << "eat\n";
return i;
}
int sleep(int i) const {
cout << "ZZZ\n";
return i;
}
typedef int (Dog::*PMF)(int) const;
// operator->* must return an object
// that has an operator():
class FunctionObject {
Dog* ptr;
PMF pmem;
public:
// Save the object pointer and member pointer
FunctionObject(Dog* wp, PMF pmf)
: ptr(wp), pmem(pmf) {
cout << "FunctionObject constructor\n";
}
// Make the call using the object pointer
// and member pointer
int operator()(int i) const {
cout << "FunctionObject::operator()\n";
return (ptr->*pmem)(i); // Make the call
}
};
FunctionObject operator->*(PMF pmf) {
cout << "operator->*" << endl;
return FunctionObject(this, pmf);
}
};
int main() {
Dog w;
Dog::PMF pmf = &Dog::run;
cout << (w->*pmf)(1) << endl;
pmf = &Dog::sleep;
cout << (w->*pmf)(2) << endl;
pmf = &Dog::eat;
cout << (w->*pmf)(3) << endl;
}
说明:
w->*pmf返回的是FunctionObject对象,而FunctionObject重载了operator(),重载函数被调用,最终pmf指向的Dog类中的方法被调用:
int operator()(int i) const {
cout << "FunctionObject::operator()\n";
return (ptr->*pmem)(i); // Make the call
}
如果需要一些额外的操作的话,在此处加入代码即可。
12.5.6 不能重载的操作符
以下操作符不能重载:
".",".*","**"