可以使用Gtk :: DrawingArea(GTKmm)作为组合而不是继承吗?

时间:2018-03-12 23:04:34

标签: c++ gtkmm gtkmm3

在GTKmm首先documentation examplemore complex clock example上,他们继承了public Gtk::DrawingArea来构建他们的应用程序。

#ifndef GTKMM_EXAMPLE_MYAREA_H
#define GTKMM_EXAMPLE_MYAREA_H

#include <gtkmm/drawingarea.h>

class MyArea : public Gtk::DrawingArea
{
public:
  MyArea();
  virtual ~MyArea();

protected:
  //Override default signal handler:
  bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override;
};

#endif // GTKMM_EXAMPLE_MYAREA_H

是否可以通过合成使用DrawingArea,而不是继承它并覆盖on_draw虚拟方法?

我想这样做,不要将我的方法/属性与从基类DrawingArea继承的Gtk::DrawingArea方法混合在一起。因此,当我访问某些内容时,我明确知道我在创作中使用了某些内容,因为我的课程定义中只有我的内容。通过继承Gtk::DrawingArea中的内容,我无法确定它是我的内容还是Gtk::DrawingArea内容,除非我知道Gtk::DrawingArea上定义的所有内容。

1 个答案:

答案 0 :(得分:1)

Short answer: no (at least for what seem to be your concern), it was not designed this way.

Longer answer:

I would like to do so, to not mix my methods/attributes with the DrawingArea methods inherited from the base class Gtk::DrawingArea.

Public inheritance vs composition should not, in my opinion, be chosen over such criteria because they have a very clear conceptual meaning. A child class publicly inheriting from a base class means (most of the time, see below) that the two classes have a is-a relationship. Composition means a has-a relationship.

So to answer your question, you should ask yourself what exactly is the relationship between the two classes (your own and Gtk::DrawingArea). Is your class some kind of drawing area? If so I would suggest public inheritance. Does your class have (or contain) a drawing area? In that case I would suggest composition.

If you violate these concepts you will almost certainly end up with hard to use and inconsistent classes and differentiating between which method is from which class will be the least of your concern.

Finally, note that there is a lot more than what is written here on inheritance and some exceptions exist. See this post for a more in depth discussion.

Hope this helps!