通过构造函数param实例化子类

instantiate childclass via constructor param

本文关键字:实例化 子类 param 构造函数      更新时间:2023-10-16

我目前正在尝试实现一个接口来创建排序算法的实例。

我有以下类:
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;
}