c++ - Implementing virtual function without a derived class
问题描述
I want to know if this is an acceptable use of a class with a virtual function.
I have a game engine project that has this code:
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);
In this game engine project (which builds to a .lib), I have a ComponentFactory.h file with the create function as virtual.
// ComponentFactory.h
class ComponentFactory
{
public:
virtual std::shared_ptr<Component> create(Json::Value definitionJSON, ComponentTypes componentType);
};
Separately, in my copterRescue project that uses my game engine .lib, I have the ComponentFactory.cpp defined. The ComponentFactory.cpp does not exist in the game engine project at all.
The copterRescue project includes the ComponentFactory.h from the game engine project.
The copterRescue project will not build unless an implementation of 'create" has been included (which is fine with me)
//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
}
In this way, I can have my "whatever" game create an overriding, game specific, component creating function that gets used within the game engine code. i.e. It allows me to inject game specific code while using my shared game engine library.
In the past, my classes with virtual functions were overriden by a derived class, and there's no derived class in this case, so is it considered bad practice?
解决方案
推荐阅读
- rust - 如何使用 From 制作可从所有其他类型转换的类型
? - android - setOnMenuItemClickListener 只执行一次
- google-sheets - 使用脚本复制谷歌表格中另一列的格式
- python - 混合抽象方法、类方法和属性装饰器时的奇怪行为
- docker - 使用 Terraform,如何为 Windows 和 Docker 创建 Azure 应用服务
- python - 如何使用python将json文件插入postgresql数据库?
- python - 根据条件附加到列表但避免添加重复项
- kubernetes - 环境变量可以在 kubernetes 清单中使用吗?
- javascript - 带有内部 JavaScript 的 HTML 页面未在移动 Safari 中打开
- swift - SwiftUI,在文本字段上使用 textContentType 会导致延迟运行 14.4.1