代码之家  ›  专栏  ›  技术社区  ›  Jens Mühlenhoff

在派生类中分配虚拟方法时,如何处理“不兼容的指针类型”?

  •  0
  • Jens Mühlenhoff  · 技术社区  · 8 年前

    我有到GLib的课程 Foo DerivedFoo .

    这个 类具有 bar () 方法:

    typedef struct _FooClass
    {
      GObjectClass parent_class;
    
      void (*bar) (Foo *self);
    } FooClass;
    

    这个 派生Foo 类派生自 并实现 巴() 方法:

    void derived_foo_bar (DerivedFoo *self);
    
    static void
    derived_foo_class_init (DerivedFooClass *klass)
    {
      FooClass *foo_class = FOO_CLASS (klass);
      // Compiler warning appears here
      foo_class->bar = derived_foo_bar;
    }
    

    警告消息是:

    warning: assignment from incompatible pointer type
    

    指针不兼容,因为 self 参数不同( Foo * 与。 DerivedFoo * ).

    这是在GObject中实现虚拟方法的正确方法吗?

    如果是,我可以/应该对编译器警告做些什么吗?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Stian Skjelstad    8 年前

    您可以让函数原型尊重虚拟基类,并使用glib宏/函数在函数中对其进行类型转换。

    void derived_foo_bar (Foo *self);
    
    static void
    derived_foo_class_init (DerivedFooClass *klass)
    {
      FooClass *foo_class = FOO_CLASS (klass);
      // Compiler warning appears here
      foo_class->bar = derived_foo_bar;
    }
    
    void derived_foo_bar (Foo *_self)
    {
      DerivedFoo *self = DERIVED_FOO (self); /* or whatever you have named this macro, using the standard GLIB semantics */
     /* If self is not compatible with DerivedFoo, a warning will be issued from glib typecasting logic */
    }