我是Vala的新手,到目前为止,我觉得它非常酷,但我无法理解继承。我读here我应该使用base()
来调用父项构造函数。好吧,很酷,似乎可以理解,但它对我不起作用。我一直在标题上得到错误。这是我的代码片段:
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);
}
}
请帮助我理解为什么Object(....)有效但不是基础(...)
不应该是同一件事吗?
答案 0 :(得分:3)
这是由于C代码的实现。当Vala生成构造函数时,它会生成两个C函数_new
函数,该函数分配内存并调用_construct
和_construct
函数来初始化对象。当您使用base()
来构造基础构造函数时,它需要一个匹配的_construct
函数来调用。并非所有用C语言编写的类都有这个;在VAPI文件中,您将找到某些构造函数的has_construct_function = false
。如果是这种情况,则不能进行连锁。基类GObject
可以从参数设置属性,因此这成为在基类中设置默认值的唯一方法。