在Gobject中,如何重写父类属于接口的方法?
GObject 类 A 实现接口 IA,B 是 A 的派生类。B 如何重写属于接口 IA 的 A 方法?
或者,这在 GObject 中可能吗?
我知道如何重写父类方法,但是当继承遇到接口时,事情似乎更加复杂。
多谢!
GObject class A implements interface IA, B is a derived class of A. How can B override A's method that is part of the interface IA?
Or, is this possible in GObject?
I know how to override parent class methods, but when inheritance meets interface, things seems to be more complicated.
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是可能的:只需使用
G_IMPLMENT_INTERFACE()
重新实现接口,或者在get_type()
函数中手动初始化它。真正的痛苦是您是否需要链接旧方法。在这种情况下,你应该玩
g_type_interface_peek_parent
获取之前的接口类。这是一个测试用例:
Yes, it is possible: just reimplement the interface as it was the first time, either using
G_IMPLEMENT_INTERFACE()
or manual initializing it in yourget_type()
function.The real pain is if you need to chain up the old method. In this case, you should play with
g_type_interface_peek_parent
to get the previous interface class.Here is a test case:
我认为更好的解决方案是使 A 的方法虚拟,而不是让 B 重新实现 A 所附加的接口(这可能需要更多的工作而不仅仅是重新定义一个函数),您可以这样做(示例应该是完整的)除了 fooable 接口定义之外):
这是我能做的最简短的例子。当您调用
fooable_foo()
时,该函数将在其 vtable 中查找您实现接口时定义的函数,即a_foo()
,它会查看 A 类的 vtable 来确定哪个实际调用的函数。 B 类定义用自己的定义覆盖 A 类的a_foo_real()
。如果您需要 B 类的b_foo_real
进行链接,那很简单(使用在 G_DEFINE_TYPE 宏中为您定义的A_CLASS(b_parent_class)->foo()
)I think a better solution would be to make A's method virtual, rather than have B re-implement the interface A is attached to (this may require more work than just redefining one function), which you can do like this (example should be complete other than the fooable interface definition):
That's as brief of an example as I can make it. When you call
fooable_foo()
the function will look at its vtable for the function defined when you implemented the interface which isa_foo()
which looks at A class's vtable to determine which function to actually call. The B class definition overrides A class'sa_foo_real()
with its own. If you need B class'sb_foo_real
to chain up, that's an easy enough (useA_CLASS(b_parent_class)->foo()
which is defined for you in the G_DEFINE_TYPE macro)