我有to GLib类Foo
和DerivedFoo
。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中实现虚拟方法的正确方法吗?
如果是,我可以/应该对编译器警告做些什么吗?
最佳答案
离开函数原型以尊重虚拟基类,并使用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 */
}