-3
class Widget{ .. }  // Widget Class

class Interface { // pure virtual functions .. } // Interface class (Abstract Class)

class WidgetType1 : public Widget, public Interface { ... } // Type 1 Widget (ComboBox) inherits widget and Interface
class WidgetType2 : public Widget, public Interface { ... } // Type 2 Widget (LineEdit) inherits widget and Interface

Widget* widget = getWidget(...);
Interface* interface = dynamic_cast<Interface*> (widget); // Convert Widget to Interface

我应该做什么访问 Widget 对象上的接口方法(基本上是 WidgetType 1/2)

我无法键入 Widget 指针引用的 WidgetType1 的转换对象

设计形象

4

2 回答 2

1

我正在将我的评论变成一个答案:我的猜测是你得到一个编译器错误,因为你忘记在dynamic_cast:中添加括号

Interface* interface = dynamic_cast<Interface*>(widget)

为了dynamic_cast在运行时正常工作,您需要使用 RTTI 编译您的项目(运行时类型信息,链接到 Wikipedia 文章)。我可能弄错了,但我相信编译器默认启用 RTTI,所以你应该知道你是否禁用了它。

于 2013-01-02T11:58:41.123 回答
0

这只是一个猜测,因为您没有向我们展示错误的实现class Widget或描述错误的性质。

class Widget{ ... };  // Widget Class
...
Interface* interface = dynamic_cast<Interface*> (widget); 

请注意,我在类规范的末尾添加了一个缺少的分号。仅此一项就可能是您的问题的原因。

另一种可能性:您对类的评论Interface特别表明为该类定义了虚拟方法。您对课程的评论Widget没有说明任何问题。Widget不是多态类,您没有为该类定义任何虚拟方法。唯一可以将指向非多态类的指针动态转换为父类指针。Interface不是 的父类,如果没有任何虚方法Widget,则创建动态类是非法的。Widget

于 2013-01-02T13:06:28.037 回答