开发者

Initializing the base class to a derived base class?

I don't think this is possible, but if it is, I'd find it very usseful.

I'm making a Gui API where the user does the paint event. Lets say I want to make a Numeric TextBox. Well it would only seem good practice for it to inherit from TextBox. The problem with this, is that the user is then stuck to reimplement the paint event for the textbox since

TextBox::paint();  

Would just call my default way of drawing it.

It would be annoying if they had to maintain all their TextBox derivatives.

Is there a way to get around this problem?

Lets say my TextBox paints a square, then the numeric part adds a circle, but the user's textbox, which derives from my TextBox draws a triangle, and 开发者_Python百科my Numeric one derives from my TextBox I want the result to be triangle, circle.

Thanks


As I say in my comment, I think the bridge pattern is actually what you want, but since you're trying to insert a user's class as a base class for your NumericField thing the way you'd do THAT is to:

template < typename Base = TextField >
struct NumericField : Base
{
 ...
  void paint() { Base::paint(); draw_circle(); }
};

Now the user could use NumericField<> or they could insert their class:

struct UserField : TextField
{
  ...
  void paint() { draw_triangle(); }
};
NumericField<UserField> my_field;

The bridge answer would look more like so:

struct TextField
{
  TextField() : extender_(new null_extender) {}
  ...
  void set_extender(extender*);
  virtual void paint() { draw_square(); extender_->paint(); }
  ...
};

struct extender { virtual void paint() = 0; };
struct null_extender { void paint() {}};
struct numeric_extender { void paint() { draw_circle(); }};

struct UserField
{
  void paint() { draw_triangle(); extender()->paint(); }
};

Lots of details missing from that, but that would sort of be the story.


Isn't the only difference between NumericTextBox and TextBox that the former only allows the input of certain characters? Do you want it to paint differently?


I'm not sure quite what you mean. Your question is not that clear.

The title seems to be asking how to call the base class initializer or constructor, is that what you want?

If this is what you want then just like this.

class TextBox
{
  public:
  TextBox() { }
  virtual ~TextBox() { }

  virtual Paint() { }
};

class NumericTextBox : public TextBox
{
  public:
  NumericTextBox() : TextBox() { }
  ~NumericTextBox() { }

};

Make sure the base class for TextBox::Paint and any other methods are declared virtual as well as the destructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜