我正在尝试使用工厂方法返回派生类,但返回类型是基类类型。根据我的理解,我认为继承可以让我这样做,显然我错了。
WeightExercise 和 CardioExercise 均派生自 Exercise。
我可以转换对象,但我认为我的设计意味着我不必那样做。有人可以指出我的错误吗?
主要
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;
}
}
最佳答案
您可以将从工厂返回的派生类分配给基类一:
ExerciseFactory ExerciseFactoryObj;
Exercice *WeightExerciseObj = ExerciseFactoryObj.createExercise(menuselection);
已编辑:
如果您确实需要访问 WeightExerciceObject 元素,请使用:
WeightExerciceObject * weight = dynamic_cast<WeightExerciceObject *>(ExerciseFactoryObj.createExercise(menuselection));
如果类不是确切的类,这将返回 NULL。您需要检查 NULL。
关于c++ - 从 BaseClass* 到 DerivedClass* 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11274043/