Think_in_CPP第十二章 操作符重载(5)

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 不能重载的操作符

以下操作符不能重载:

".",".*","**"




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值