我理解得不是太清楚,请大家帮我看看。 g++ a.cpp -o test error:

  command.cpp: In function ‘int main()’:
  command.cpp:92: error: no matching function for call to ‘SimpleCommand<MyClass>::SimpleCommand(MyClass&, <unresolved overloaded function type>)’
  command.cpp:29: note: candidates are: SimpleCommand<ReceiverType>::SimpleCommand(ReceiverType&, void (ReceiverType::*)()) [with ReceiverType = MyClass]
  command.cpp:26: note: SimpleCommand<MyClass>::SimpleCommand(const SimpleCommand<MyClass>&)

-----------------------------------------------------

  #include <stdio.h>
  #include <stdlib.h>
  #include <string>
  #include <vector>
  #include <algorithm>
  using namespace std;
  class MyClass
  {
  public:
  void Display1()
  {
  printf("MyClass.Display1() called\n");
  }
  void Display2()
  {
  printf("MyClass.Display2() called\n");
  }
  };
  class Command
  {
  public:
  virtual ~Command() {}
  virtual void Execute()=0;
  };
  template<class ReceiverType>
  class SimpleCommand:public Command{
  public:
  typedef void (ReceiverType::*Action)();//function ptr
  SimpleCommand(ReceiverType &r,Action a)
  :_receiver(r),
  _action(a)
  {
  }
  void Execute()
  {
  (_receiver._action)();
  }
  private:
  ReceiverType _receiver;
  Action _action;
  };
  class NormalCommand1:public Command{
  public:
  NormalCommand1(MyClass &r)
  :_receiver(r)
  {
  }
  void Execute()
  {
  _receiver.Display1();
  }
  private:
  MyClass _receiver;
  };
  class NormalCommand2:public Command{
  public:
  NormalCommand2(MyClass &r)
  :_receiver(r)
  {
  }
  void Execute()
  {
  _receiver.Display2();
  }
  private:
  MyClass _receiver;
  };
  class MacroCommand:public Command
  {
  public:
  MacroCommand() {}
  void Add(Command *c)
  {
  _commands.push_back(c);
  }
  void Remove(Command *c)
  {
  remove(_commands.begin(),_commands.end(),c);
  }
  virtual void Execute()
  {
  for(vector<Command *>::iterator iter=_commands.begin();iter!=
_commands.end();iter++)
  (*iter)->Execute();
  }
  private:
  vector<Command *>_commands;
  };
  int main()
  {
  MyClass m;
  Command *a=new SimpleCommand<MyClass>(m,m.Display1);
  a->Execute();
  Command *b=new NormalCommand1(m);
  b->Execute();
  Command *c=new NormalCommand2(m);
  c->Execute();
  MacroCommand micro_command;
  micro_command.Add(a);
  micro_command.Add(b);
  micro_command.Add(c);
  micro_command.Execute();
  return 0;
  }

推荐图书

  • C++ Primer中文版(第4版)
  • More Effective C++:35个改善编程与设计的有效方法(中文版)
  • 设计模式:可复用面向对象软件的基础


1个回答

void Execute()
    {
        (_receiver.*_action)();   /// 注意这个地方
    }


Command *a=new SimpleCommand<MyClass>(m,&MyClass::Display1);