无法将超类强制转换为子类

时间:2015-05-10 10:08:39

标签: c++ inheritance rendering abstraction

我目前正在我的游戏和渲染引擎之间编写一个抽象层。不幸的是,我遇到了一个问题:我似乎无法将超类(抽象接口)转换为子类(具体引擎的实现)。这是我的代码:

IInitationSettings.h

class IInitationSettings {};

OxygineInitiationSettings.h

#include "IInitiationSettings.h"
#include "core/oxygine.h"
class OxygineInitiationSettings : public IInitationSettings, public oxygine::core::init_desc {
public:
    OxygineInitiationSettings(const char* title, bool vsync, bool fullscreen, int width, int height);
};

OxygineInitiationSettings.cpp

#include "OxygineInitiationSettings.h"
OxygineInitiationSettings::OxygineInitiationSettings(const char* title, bool vsync, bool fullscreen, int width, int height) : oxygine::core::init_desc() {
    this->title = title;
    this->vsync = vsync;
    this->fullscreen = fullscreen;
    this->w = width;
    this->h = height;
}

抽象的init方法:

static void init(IInitiationSettings& initSettings);
void GraphicsFactory::init(IInitiationSettings& initSettings){
#ifdef USE_OXYGINE_RENDERING
    OxygineInitiationSettings settings = initSettings; //Does not work
    oxygine::core::init_desc desc = initSettings; // Does not work
    oxygine::core::init((oxygine::core::init_desc)((OxygineInitiationSettings)initSettings)); //Does not work
#endif
}

如何将抽象接口转换为具体实现?我想添加一个newInitiationSettings-Method,它将返回一个IInitiationSettings对象,我将它传递给init方法,以便有一个干净的代码。 (我希望我的游戏代码看起来像这样:

GraphicsFactory::init(GraphicsFactory::newInitiationSettings(args));

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

这里的根本错误是尝试将对象本身转换为抽象init方法中的其他类型。向上(即向基类)转换会导致object slicing,因为它只复制基类的数据。这通常很糟糕,但向下投射可能是不可能的。所以编译器不会让你。

您真正想要做的是在参考或指针级别工作。松散地说,引用是指针的语法糖,指向对象的指针可以替代指向其基类之一的指针。这就是为什么您可以通过derived类型的参数传递base&的原因。但是当您尝试恢复derived时,您必须要求derived&derived*。在你的情况下,这看起来更像是其中之一:

static_cast<OxygineInitiationSettings&>(initSettings) // or
dynamic_cast<OxygineInitiationSettings&>(initSettings)

或者,如果你需要一个指针,也许这个:

static_cast<OxygineInitiationSettings*>(&initSettings) // or
dynamic_cast<OxygineInitiationSettings*>(&initSettings)

如果您确定initSettings会引用OxygineInitiationSettings个实例,则可以而且应该使用static_cast代替dynamic_cast。如果您不确定,您应该确定或使用dynamic_cast代替static_cast。请注意,动态引用强制转换将引发std::bad_cast异常,如果initSettings引用的实际对象实际上不是OxygineInitiationSettings,则动态指针强制转换将返回空指针。

答案 1 :(得分:2)

Dynamic_cast可以从虚拟类执行,即具有虚方法的类。只需添加 dummy()方法:

class IInitationSettings {
    virtual void dummy() {}
};

并从隐式转换为动态转换:

void GraphicsFactory::init(IInitationSettings& initSettings) {
    OxygineInitiationSettings settings =
        dynamic_cast<OxygineInitiationSettings&>(initSettings); //Does indeed work
}

会解决问题。