我想知道这是否可以接受使用具有虚函数的类。
我有一个包含此代码的游戏引擎项目:
std::unique_ptr<ComponentFactory> componentFactory = std::make_unique<ComponentFactory>();
auto component = std::static_pointer_cast<BrainComponent>(componentFactory->create(definitionJSON, ComponentTypes::BRAIN_COMPONENT));
addComponent(component, ComponentTypes::BRAIN_COMPONENT);
在这个游戏引擎项目(构建为 .lib)中,我有一个 ComponentFactory.h 文件,其创建函数为虚拟。
// ComponentFactory.h
class ComponentFactory
{
public:
virtual std::shared_ptr<Component> create(Json::Value definitionJSON, ComponentTypes componentType);
};
另外,在使用我的游戏引擎 .lib 的 copterRescue 项目中,我定义了 ComponentFactory.cpp。 ComponentFactory.cpp 在游戏引擎项目中根本不存在。
copterRescue 项目包括来自游戏引擎项目的 ComponentFactory.h。
除非包含“create”的实现(这对我来说很好),否则不会构建 copterRescue 项目
//ComponentFactory.cpp
#include "ComponentFactory.h"
std::shared_ptr<Component> ComponentFactory::create(Json::Value definitionJSON, ComponentTypes componentType)
{
//Do stuff specific to this game to create and return a particular Component
}
通过这种方式,我可以让我的“任何”游戏创建一个覆盖的、特定于游戏的组件创建函数,该函数在游戏引擎代码中使用。即它允许我在使用我共享的游戏引擎库时注入游戏特定的代码。
过去,我的带有虚函数的类被派生类覆盖,在这种情况下没有派生类,所以这被认为是不好的做法吗?