首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问C++编译有关问题,关于模板类和虚函数

2012-04-10 
请教C++编译问题,关于模板类和虚函数我理解得不是太清楚,请大家帮我看看。g++ a.cpp -o testerror:command.

请教C++编译问题,关于模板类和虚函数
我理解得不是太清楚,请大家帮我看看。
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;


  }

[解决办法]
Command *a=new SimpleCommand<MyClass>(m,&MyClass::Display1);
[解决办法]
成员函数指针使用错误, 看一下怎么成员函数指针是怎么用的吧
[解决办法]

C/C++ code
void Execute()    {        (_receiver.*_action)();   /// 注意这个地方    }
[解决办法]
探讨
Command *a=new SimpleCommand<MyClass>(m,&amp;MyClass::Display1);

[解决办法]
探讨

C/C++ code

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

[解决办法]
http://www.cnblogs.com/chenyuming507950417/archive/2012/01/02/2310114.html

热点排行