通过基类抽象方法调用

时间:2018-01-31 01:49:47

标签: c++ abstract-class virtual

我有一个界面,用户从中派生出多个我不知道的类,但我仍然想调用这些派生类的常用方法Run().

Event类旨在成为一个界面,因此我知道如何调用我的未知 UserEvents派生类,因为它们都必须具有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);
 }

1 个答案:

答案 0 :(得分:2)

我拿了你的示例代码(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上的生活演示)

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