【问题标题】:How to deal with "incompatible pointer type" when assigning virtual methods in a derived class?在派生类中分配虚拟方法时如何处理“不兼容的指针类型”?
【发布时间】:2016-04-23 06:31:59
【问题描述】:

我有 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 中实现虚方法的正确方法吗?

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

【问题讨论】:

  • 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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多