【发布时间】:2014-12-01 17:43:53
【问题描述】:
我正在尝试覆盖下面的virtual void clear();:
class DerivatedGraphicsContext : public osg::GraphicsContext {
public:
void clear() { /* Do something */ }
};
但是,我需要使用 osg::GraphicsContext::createGraphicsContext 方法初始化我的 DerivatedGraphicsContext 对象:
DerivatedGraphicsContext* dgc = (DerivatedGraphicsContext*)osg::GraphicsContext::createGraphicsContext(..);
问题是当我现在调用 dgc->clear(); 时,它会调用 osg::GraphicsContext::clear() 方法。
我已尝试强制转换 static_cast 或 dynamic_cast,但我不确定这是否可行,或者我是否需要在派生类中重新实现 createGraphicsContext 才能访问 clear() 方法由DerivatedGraphicsContext 类。
任何建议将不胜感激!
编辑:
createGraphicsContext(..) 返回osg::GraphicsContext*,它是通过调用一些 Windows API 创建的。
因为 osg::GraphicsContext 有纯虚函数,所以类是抽象的,不实现方法就无法实例化。因此,甚至无法使用osg::GraphicsContext* gc = new osg::GraphicsContext(),当然DerivatedGraphicsContext 也是如此。
由于我不能使用 new 关键字,我无法将其内容复制到 DerivatedGraphicsContext,我可以返回它的指针。
来源在这里:
【问题讨论】:
-
你需要确认两件事。 1) 函数签名是否相同 2) osg::GraphicsContext 中的 clear() 函数是否标记为虚拟
-
试试
... = &dynamic_cast<DerivatedGraphicsContext&>(*osg::GraphicsContext::createGraphicsContext(..));并告诉我们结果 -
第三件事:
createGraphicsContext()真的创建了 DerivativedGraphicContext 吗?因为转换对象指针不会改变对象在构造时获得的虚函数... -
是的,在 osg::GraphicsContext 中 clear() 函数是虚拟的,两者都有返回类型 void 没有任何参数。的:
... = &dynamic_cast<DerivatedGraphicsContext&>(*osg::GraphicsContext::createGraphicsContext(..));导致 std::bad_cast 异常。createGraphicsContext()返回一个osg::GraphicsContext*,这就是我进行强制转换的原因。 -
如果在创建对象的时候就决定了虚函数,我想应该可以新建一个
DerivatedGraphicsContext,然后从osg::GraphicsContext复制数据,有点类似思路@JohannesSchaub-litb 的
标签: c++ function overriding virtual