operator->*

  1. #include <iostream>
  2. using namespace std;
  3. class Dog{
  4. public:
  5.  int run(int i)const{
  6.   cout<<"run"<<endl;
  7.   return i;
  8.  }
  9.  int eat(int i)const{
  10.   cout<<"eat"<<endl;
  11.   return i;
  12.  }
  13.  int sleep(int i)const{
  14.   cout<<"sleep"<<endl;
  15.   return i;
  16.  }
  17. typedef int (Dog::*PMF)(intconst;
  18.  class FunctionObject{
  19.   Dog* dog;
  20.   PMF pmem;
  21.  public:
  22.   FunctionObject(Dog* d,PMF pmf):dog(d),pmem(pmf){
  23.    cout<<"FunctionObject constructor"<<endl;
  24.   }
  25. int operator()(int i)const{
  26.    cout<<"FunctionObject::operator()"<<endl;
  27.    return (dog->*pmem)(i);
  28.   }
  29.  };
  30. FunctionObject operator->*(PMF pmf){
  31.   cout<<"operator->*"<<endl;
  32.   return FunctionObject(this,pmf);
  33.  }
  34. };
  35. void test(){
  36.  Dog dog;
  37.  Dog::PMF pmf=&Dog::run;
  38.  cout<<(dog->*pmf)(1)<<endl;
  39.  pmf=&Dog::eat;
  40.  cout<<(dog->*pmf)(2)<<endl;
  41.  pmf=&Dog::sleep;
  42.  cout<<(dog->*pmf)(3)<<endl;

你可能感兴趣的:(operator->*)