我目前正在我的游戏和渲染引擎之间编写一个抽象层.不幸的是,我遇到了一个问题:我似乎无法将超类(抽象接口)强制转换为子类(具体引擎的实现).这是我的代码:
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));
)
有任何想法吗?
解决方法:
这里的根本错误是尝试将对象本身转换为抽象init方法中的其他类型.向上(即向基类)转换会产生object slicing,因为它只是基类的数据的副本.这通常很糟糕,但向下投射可能是不可能的.所以编译器不会让你.
你真正想做的是在引用或指针级别工作.松散地说,引用是指针的语法糖,指向对象的指针可以替代指向其基类之一的指针.这就是为什么你可以通过类型base&的参数传递派生的原因.但是当你试图让你的派生回来时,你必须要求派生的&或派生的*.在您的情况下,这看起来更像是其中之一:
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,则动态指针强制转换将返回空指针.