在vala中覆盖方法

时间:2014-10-31 10:20:10

标签: gtk3 vala

作为一个经验,我正在像这样在vala中扩展Gtk.HeaderBar类,以便有一个Button而不是标题/副标题标签:

using Gtk;

public class WebBrowserHeaderBar : HeaderBar {

    private Button title_widget;

    public WebBrowserHeaderBar(){
        this.show_close_button = true;

        title_widget = new Button.with_label("title");

        this.set_custom_title(title_widget);
    }

    public void set_title(string title){
        title_widget.label = title;
    }

}

然后我就像这样使用它:

public class MainWindow: Window {

    private WebBrowserHeaderBar header;

    public MainWindow() {
        //this.title = MyWeb.APP_TITLE;

        this.window_position = WindowPosition.CENTER;
        this.destroy.connect (Gtk.main_quit);
        set_default_size (300, 200);

        header = new WebBrowserHeaderBar();
        header.set_title (MyWeb.APP_TITLE);
        this.set_titlebar(header);
    }

}

这有效,但是在编译时我收到以下警告:

WebBrowserHeaderBar.vala:15.2-15.22: warning: WebBrowserHeaderBar.set_title hides inherited method `Gtk.HeaderBar.set_title'. Use the `new' keyword if hiding was intentional
    public void set_title(string title){
    ^^^^^^^^^^^^^^^^^^^^^
Compilation succeeded - 1 warning(s)

如果我改变我的方法public override void set_title(string title){,它将无法编译:

WebBrowserHeaderBar.vala:15.2-15.31: error: WebBrowserHeaderBar.set_title: no suitable method found to override
    public override void set_title(string title){
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)

为什么我会这样?如何摆脱警告和/或成功覆盖set_title方法?

1 个答案:

答案 0 :(得分:4)

您只能覆盖abstractvirtual的方法。其他方法无法覆盖,但您可以使用new关键字隐藏它们:

public new void set_title (string title) {
     title_widget.label = title;
}

如果引用的类型为WebBrowserHeaderBar或其子类型,则将调用此方法。如果引用的类型为HeaderBar或其中一个超类,则将使用原始set_title

这是一个有点龙的功能。

相关问题