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

时间:2016-04-22 19:35:36

标签: c compiler-warnings glib gobject virtual-method

我有GLib课程FooDerivedFoo

Foo类有一个bar ()方法:

typedef struct _FooClass
{
  GObjectClass parent_class;

  void (*bar) (Foo *self);
} FooClass;

DerivedFoo类派生自Foo并实现bar ()方法:

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 个答案:

答案 0 :(得分:3)

您保留函数原型以尊重虚拟基类,并使用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 */
}