通过构造函数param实例化子类
instantiate childclass via constructor param
我目前正在尝试实现一个接口来创建排序算法的实例。
我有以下类:
ISortAlgorithm->抽象(接口"类")
AlgorithmModule->with a static function->
static ISortAlgorithm* CreateSortInstanceOf(EAlgorithm AlgorithmEnum)
和一个类容器(命名空间算法)与ISortAlgorithm的子类类似->
class SelectionSort : public ISortAlgorithm
还存在每个实现算法的枚举->
enum EAlgorithm {SELECTIONSORT, BUBBLESORT, ...}
在运行时,有人想使用我模块中的算法,他会调用:
AlgorithmModule::CreateSortInstanceOf(/*enum of desired algorithm */)
我在这个功能中做的第一件事是->
{
switch (enumparam)
{
case (EAlgorithm::INSERTSORT) :
return SortAlgorithm = new Algorithms::InsertSort();
break;
case (blah): [..]
}
这已经起作用了。但现在我想了一种更容易的方法,我想到了可以使用构造函数的想法,并尝试了:
class InsertSort : public ISortAlgorithm
{
public:
InsertSort() : ISortAlgorithm(EAlgorithm::INSERTSORT){}
}
class SelectionSort : public ISortAlgorithm
{
public:
SelectionSort() : ISortAlgorithm(EAlgorithm::SELECTIONSORT) {}
}
除此之外,我将CreateSortInstanceOf修改为:
static ISortAlgorithm* CreateSortInstanceOf(EAlgorithm AlgorithmEnum)
{
ISortAlgorithm* SortAlgorithm = new ISortAlgorithm(AlgorithmEnum);
return SortAlgorithm;
}
因此,我们的意图是使用构造函数param来调用正确的子类。这意味着我不必为将来想要实现的任何算法更改这个函数的代码。然而,编译器当然抱怨说,我无法实例化抽象类,我认为另一个问题是ctor的非继承性。
但我确信,我的意图应该是可能的,所以我需要你的帮助来指出我在这里错过了什么。
向致以最良好的问候
这是一种做你想做的事情的方法,即使它不一定是最好的:
#include "stdafx.h"
#include "map"
enum EAlgorithm { SELECTIONSORT=0, INSERTSORT=1 };
class ISortAlgorithm;
typedef ISortAlgorithm * (*fct)(void);
std::map mapCreator;
class ISortAlgorithm
{
public:
ISortAlgorithm(void) {};
virtual void run(void) = 0;
static ISortAlgorithm* CreateSortInstanceOf(EAlgorithm AlgorithmEnum)
{
std::map::iterator it = mapCreator.find(AlgorithmEnum);
if (it == mapCreator.end())
return NULL;
return it->second();
}
};
class InsertSort : public ISortAlgorithm
{
public:
InsertSort(){}
virtual void run(void){};
static ISortAlgorithm * Create(void)
{
return (ISortAlgorithm*) new InsertSort();
};
};
class SelectionSort : public ISortAlgorithm
{
public:
SelectionSort(){};
virtual void run(void){};
static ISortAlgorithm * Create(void)
{
return (ISortAlgorithm*) new SelectionSort();
};
};
int _tmain(int argc, _TCHAR* argv[])
{
mapCreator.insert(std::pair(EAlgorithm::INSERTSORT, InsertSort::Create));
mapCreator.insert(std::pair(EAlgorithm::SELECTIONSORT, SelectionSort::Create));
ISortAlgorithm * pt1 = ISortAlgorithm::CreateSortInstanceOf(EAlgorithm::INSERTSORT);
ISortAlgorithm * pt2 = ISortAlgorithm::CreateSortInstanceOf(EAlgorithm::SELECTIONSORT);
return 0;
}
相关文章:
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何初始化矢量的模板化子类
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- ATL::CComContainedObject<contained>: C2259 无法实例化抽象类
- C++ 如何从虚拟类的模板化子类中获取数据?
- 尝试实例化模板类的对象时出现"No Matching Constructor"错误
- 如何使用其中一个具体类实例化抽象类?
- 在实例化封闭类模板之后,我们可以声明模板类成员的部分专用化吗
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- 无法实例化抽象类错误
- 实例化新类时未调用的方法
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 访问使用接口实例化的类的私有成员
- 如何在不实例化派生类的情况下管理一组派生类枚举
- 从C++中的父类实例访问子类方法
- 通过构造函数param实例化子类
- C++ 无法实例化 abstaract 类的子级
- 从基类模板化列表中实例化子类对象
- C++用纯虚拟函数实例化抽象类的子类
- 实例化子类的多态性问题