构造函数
Vala支持两种略有不同的构造方案:我们将重点讨论Java/C#风格的构造方案,另一种是GObject风格的构造方案。
Vala不支持构造函数重载的原因与方法重载不被允许的原因相同,这意味着一个类不能有多个同名构造函数。但这并不构成问题,因为Vala支持命名构造函数。如果您需要提供多个构造函数,可以为它们添加不同的名称后缀:
public class Button : Object {public Button() {}public Button.with_label(string label) {}public Button.from_stock(string stock_id) {}
}
实例化的方式与之对应:
new Button();
new Button.with_label("点击我");
new Button.from_stock(Gtk.STOCK_OK);
你可以通过this()
或this.``*名称后缀*
()`实现构造函数链式调用:
public class Point : Object {public double x;public double y;public Point(double x, double y) {this.x = x;this.y = y;}public Point.rectangular(double x, double y) {this(x, y);}public Point.polar(double radius, double angle) {this.rectangular(radius * Math.cos(angle), radius * Math.sin(angle));}
}void main() {var p1 = new Point.rectangular(5.7, 1.2);var p2 = new Point.polar(5.7, 1.2);
}
析构函数
虽然Vala会自动管理内存,但如果您选择使用指针进行手动内存管理(后续详述),或需要释放其他资源时,可能需要自定义析构函数。语法与C#和C++一致:
class Demo : Object {~Demo() {stdout.printf("in destructor");}
}
由于Vala的内存管理基于引用计数而非追踪式垃圾回收,析构函数的执行是确定性的,可用于实现资源管理的RAII模式(关闭流、数据库连接等)。