【发布时间】:2016-04-23 06:31:59
【问题描述】:
我有 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 中实现虚方法的正确方法吗?
如果是这样,我可以/应该对编译器警告做些什么吗?
【问题讨论】:
-
DerivedFoo是如何从Foo派生而来的? C中没有继承。 -
这个问题是开始争论strict aliasing rule的好方法。
-
您可以将其转换为
foo_class->bar = (void (*)(Foo *))derived_foo_bar;。我想明智地使用typedef和/或宏会让它看起来不那么难看! -
@atturi 有inheritance in GObject。
标签: c compiler-warnings glib gobject virtual-functions