通过基础class抽象方法调用

Call through the base class abstract method

我有一个接口,用户从中导出多个我不知道的classes,但我仍然想调用这些派生的class es常用方法Run().

Event class 旨在成为一个接口,所以我知道如何调用我的 unknown UserEvents derived class,因为他们都必须实施 Run() 方法。

我目前有一些代码并收到 CallEvent can't allocate an abstract Event 的错误。我理解错误,但不知道如何才能正确执行。

这是一些最简单的代码示例 (WandBox):

#include <iostream>

class Event
 {
 public: 
      virtual void Run(int Param) = 0;
 };

 // This is a user event and I have no idea what the class name is,
 // but I still have to call it's method Run() that is common to the interface "Event"
 class UserEvent : public Event
 {
 public:
      virtual void Run(int Param) { std::cout << "Derived Event Dispatched " << Param << std::endl;};
 };

 // This parameter is of pure abstract base class Event because
 // I have no idea what my user class is called.
 void CallEvent(Event WhatEvent)
 {
      WhatEvent.Run(123);
 };

 int main()
 {
      std::cout << "Hello World!" << std::endl;
      UserEvent mE;
      CallEvent(mE);
 }

我使用了您的示例代码 (Like so) 并尝试将其制作成 运行(用于说明):

#include <iostream>

class Event {
  public: 
    virtual void Run(int Param) = 0;
};

// This is a user event and I have no idea what the class name is,
// but I still have to call it's method Run() that is common to the interface "Event"
class UserEvent: public Event {
  public:
    virtual void Run(int Param)
    {
      std::cout << "Derived Event Dispatched " << Param << std::endl;
    }
};

// This parameter is of pure abstract base class Event because
// I have no idea what my user class is called.
void CallEvent(Event *WhatEvent)
{
  std::cout << "in CallEvent(Event *WhatEvent):" << std::endl;
  // Huh? WhatEvent = new Event();
  // wrong: WhatEvent.Run(123);
  // Instead, use ->.
  // For pointers, check for non-nullptr is very reasonable:
  WhatEvent->Run(123);
  // obsolete: delete WhatEvent;
}

// second approach using a reference (as recommended in comments):
void CallEvent(Event &WhatEvent)
{
  std::cout << "in CallEvent(Event &WhatEvent):" << std::endl;
  WhatEvent.Run(123); // for references - select operator . is fine
}

int main()
{
  std::cout << "Hello World!" << std::endl;
  /* nullptr does not make sense:
   * UserEvent *mE = nullptr;
   * Go back to original approach:
   */
  UserEvent mE;
  CallEvent(&mE); // calling the first (with Event*)
  CallEvent(mE); // calling the second (with Event&)
  return 0;
}

现在可以编译运行了。输出:

Hello World!
in CallEvent(Event *WhatEvent):
Derived Event Dispatched 123
in CallEvent(Event &WhatEvent):
Derived Event Dispatched 123

ideone 上的生活演示)

我在示例代码中的注释中注释了每个修改。