问题
I'm new to Vala and so far I think it's pretty cool but I'm having trouble understanding inheritance. I read here that I should use base()
to call the parents constructor. Alright, cool, seems understandable but It din't work for me. I kept getting the error on the title. Here is my snippet to show:
public class MyBox : Gtk.Box {
public MyBox(Gtk.Orientation orientation, int spacing) {
// I have to this
this.set_orientation(orientation);
this.set_spacing(spacing);
// I want to do this:
base(orientation, spacing);
//workaround is this:
Object(orientation: orientation, spacing: spacing);
}
}
Please help me understand why Object(....) works but not base(...)
Shouldn't it be the same thing?
回答1:
This is due to implementation of the C code. When Vala generates a constructor, it generates two C functions a _new
function that allocates memory and calls the _construct
and a _construct
function that initialises the object. When you case the base constructor using base()
, it needs a matching _construct
function to call. Not all the classes written in C have this; in the VAPI file, you will find has_construct_function = false
for some constructors. If this is the case, no chain-up can be done. The base GObject
can set properties from arguments, so this becomes the only way to set defaults in the base class.
来源:https://stackoverflow.com/questions/29872925/chain-up-to-gtk-box-new-not-supported