c++ - 从 BaseClass* 到 DerivedClass* 的无效转换

标签 c++ inheritance c++11

我正在尝试使用工厂方法返回派生类,但返回类型是基类类型。根据我的理解,我认为继承可以让我这样做,显然我错了。

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/

相关文章:

c# - 仅允许在 C# 中父类(super class)的程序集上实例化子类

C++ 继承 - 引用类型的无效初始化

单元的 C++ 可用 "literal suffix code"

c++ - 将属性表应用到空的 C++ Visual Studio 项目

C++,复制集到 vector

c++ - 带空字符的 STL basic_string 长度

c++ - 与观察者指针共享指针

c++ - ecCodes(grib阅读库)不释放内存

java - 类型不匹配 : cannot convert from List<capture#2-of ? 将 IDto> 扩展为 List<FollowingResponseDto>

c++ - 中继可变参数模板参数时出现 Visual Studio 错误