【发布时间】:2015-04-13 07:31:40
【问题描述】:
我目前正在尝试实现一个接口来创建排序算法的实例。
我有以下类:
ISortAlgorithm -> 抽象(接口”类)
AlgorithmModule -> 带有静态函数 ->
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;
}
所以意图是,使用构造函数参数来调用正确的子类。这意味着我不必为将来要实现的任何算法更改此函数的代码。但是,编译器当然会抱怨,我无法实例化抽象类,我认为另一个问题是 ctor 的非继承。
但我确信,我的意图应该是可能的,所以我需要你的帮助来指出我在这里缺少的东西。
最好的问候
【问题讨论】:
标签: c++ inheritance constructor