0

I'm using MoSync / MAUI to create an mobile application prototype, but I'm facing a problem with the class inheritance:

The class hierarchy for the standard MAUI widgets is:

Widget
    EditBox
    Label
    ListBox
    ...

Then, because I want to add an standard behavior to all the widgets, I made an separate class to define that behavior:

class xFocusControl:
public:
    void method1() {};
    void method2() {};
    int member1; 
    ....

and subclass each widget type:

class xEditBox: public xFocusCtrl, public EditBox 
{
public:
    ...
}

class xLabel: public xFocusCtrl, public Label 
{
public:
    ...
}

...

Then, in several places I need to access to all the widgets using the MoSync getChildren() function, defined as:

const Vector<Widget*>& MAUI::Widget::getChildren()

My problem is: given this hierarchy, I can iterate over all the childrens as but cannot access to the new behavior (e.g: widget->member1) without casting. But, how can I generically cast each widget to its class? So far, I'm testing each possible widget class with some code like

member1 = 0;
if (isType <xLabel*> (widget)) {
    member1 = ((xLabel*) (widget))->member1; 
}

if (isType <xEditBox*> (widget)) {
    member1 = ((xEditBox*) (widget))->member1; 
}
...

but it looks bad to me: I'm a C++ newbie, and much more proficient in dynamic languages as Python, so maybe I'm taking a wrong approach.

Do you mind a better way to do this?

As noted in the comments, I'm using regular cast instead of dynamic_cast because MoSync don't supports dynamic_cast so far

4

1 回答 1

1

You should use dynamic_cast

xLabel* label = dynamic_cast<xLabel*>(widget);
if (label)
{
    member1 = label->member1;
}
// dynamic cast failed
else
{
}
于 2012-07-28T23:10:27.017 回答