我试图使用工厂方法来返回派生类,但返回类型是基类类型。根据我的理解,我认为继承可以让我做到这一点,显然我错了。无效从BaseClass *转换为DerivedClass *
WeightExercise和CardioExercise都来自练习。
我可以抛出物体,但我认为我的设计意味着我不必这样做。有人能指出我的错误吗?
主要
ExerciseFactory ExerciseFactoryObj;
WeightExercise *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
工厂类
class ExerciseFactory
{
public:
ExerciseFactory();
~ExerciseFactory();
Exercise* createExercise(int exercisetype);
private:
static WeightExercise* createWeightExercise() { return new WeightExercise(); }
static CardioExercise* createCardioExercise() { return new CardioExercise(); }
};
工厂实现
Exercise* ExerciseFactory::createExercise(int exercisetype)
{
if (1 == exercisetype)
{
return this->createWeightExercise();
}
else if (2 == exercisetype)
{
return this->createCardioExercise();
}
else
{
cout << "Error: No exercise type match" << endl;
}
}
您正在将返回值分配给派生类。你必须将它分配给BaseClass * – MBen