Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在没有派生类的情况下实现虚函数_C++ - Fatal编程技术网

C++ 在没有派生类的情况下实现虚函数

C++ 在没有派生类的情况下实现虚函数,c++,C++,我想知道这是否是一个带有虚拟函数的类的可接受的用法 我有一个游戏引擎项目,其中包含以下代码: std::unique_ptr<ComponentFactory> componentFactory = std::make_unique<ComponentFactory>(); auto component = std::static_pointer_cast<BrainComponent>(componentFactory->create(definit

我想知道这是否是一个带有虚拟函数的类的可接受的用法

我有一个游戏引擎项目,其中包含以下代码:

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);
std::unique_ptr componentFactory=std::make_unique();
auto-component=std::static_-pointer_-cast(componentFactory->create(definitionJSON,ComponentTypes::BRAIN_-component));
addComponent(component,ComponentTypes::BRAIN_component);
在这个游戏引擎项目(构建为.lib)中,我有一个ComponentFactory.h文件,其中create函数为virtual

// ComponentFactory.h

class ComponentFactory
{
public:

    virtual std::shared_ptr<Component> create(Json::Value definitionJSON, ComponentTypes componentType);

};
//组件工厂.h
类组件工厂
{
公众:
虚拟std::shared_ptr create(Json::Value definitionJSON,ComponentTypes componentType);
};
另外,在使用game engine.lib的copterRescue项目中,我定义了ComponentFactory.cpp。ComponentFactory.cpp在游戏引擎项目中根本不存在

copterRescue项目包括来自游戏引擎项目的ComponentFactory.h

除非包含“create”的实现,否则不会构建copterRescue项目(这对我来说很好)

//ComponentFactory.cpp
#包括“ComponentFactory.h”
std::shared_ptr ComponentFactory::create(Json::Value definitionJSON,ComponentTypes componentType)
{
//做一些特定于这个游戏的事情来创建和返回一个特定的组件
}
通过这种方式,我可以让我的“任意”游戏创建一个覆盖性的、特定于游戏的组件创建函数,该函数在游戏引擎代码中使用。也就是说,它允许我在使用共享游戏引擎库时注入特定于游戏的代码


在过去,我的带有虚拟函数的类被派生类覆盖,而在这种情况下没有派生类,所以这被认为是不好的做法吗?

使用相同事物的替代实现并通过依赖项注入引入它们并不奇怪,但可能没有必要是
虚拟的,除非这听起来像是在谈论编译时差异化,它给了您比运行时差异化更多的选择。
//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
}