This question already has answers here:
C++ virtual method not called as desired
(4个答案)
2年前关闭。
我有一个接口(interface),用户可以从该接口(interface)派生我不知道的多个类,但我仍然想将这些派生类称为通用方法
我目前有一些代码,并得到一个错误
这是一些最小的代码示例(WandBox):
现在,它是可编译且可运行的。输出:
(ideone上的生活演示)
我在示例代码中的注释中注释了每个修改。
(4个答案)
2年前关闭。
我有一个接口(interface),用户可以从该接口(interface)派生我不知道的多个类,但我仍然想将这些派生类称为通用方法
Run().
Event
类旨在用作接口(interface),因此我知道如何调用我的未知 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);
}
最佳答案
我获取了您的示例代码(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上的生活演示)
我在示例代码中的注释中注释了每个修改。