Glib学习笔记(三)
你将学到什么
如何实现Object的方法
Object的方法
Object的public方法
在头文件声明一个函数,然后在源文件中实现函数即可
/* declaration in the header. */
void viewer_file_open (ViewerFile *self,
GError **error);
/* implementation in the source file */
void
viewer_file_open (ViewerFile *self,
GError **error)
{
g_return_if_fail (VIEWER_IS_FILE (self));
g_return_if_fail (error == NULL || *error == NULL);
/* do stuff here. */
}
Object的public虚函数
GObject通过函数指针的方式来模拟C++语言的虚函数实现,具体步骤如下:
- 在类结构定义里面设置一个函数指针,然后定义一个public方法(用来调用函数指针)
- 在源文件里实现public方法(核心就是调用函数指针)
- 在基类的
class_init
函数设虚函数指针,指向函数的实现,或者设置为NULL
来模拟纯虚函数(子类必须实现函数并设置设置函数指针)
下面的open
就是纯虚函数,close
就是虚函数
/* declaration in viewer-file.h. */
#define VIEWER_TYPE_FILE viewer_file_get_type ()
G_DECLARE_DERIVABLE_TYPE (ViewerFile, viewer_file, VIEWER, FILE, GObject)
struct _ViewerFileClass
{
GObjectClass parent_class;
/* stuff */
void (*open) (ViewerFile *self,
GError **error);
void (*close) (ViewerFile *self,
GError **error);
/* Padding to allow adding up to 12 new virtual functions without
* breaking ABI. */
gpointer padding[12];
};
void viewer_file_open (ViewerFile *self,
GError **error);
void viewer_file_close (ViewerFile *self,
GError **error);
/* implementation in viewer-file.c */
void viewer_file_open (ViewerFile *self,
GError **error);
static void
viewer_file_real_close (ViewerFile *self,
GError **error)
{
/* Default implementation for the virtual method. */
}
static void
viewer_file_class_init (ViewerFileClass *klass)
{
/* this is not necessary, except for demonstration purposes.
*
* pure virtual method: mandates implementation in children.
*/
klass->open = NULL;
/* merely virtual method. */
klass->close = viewer_file_real_close;
}
void
viewer_file_open (ViewerFile *self,
GError **error)
{
ViewerFileClass *klass;
g_return_if_fail (VIEWER_IS_FILE (self));
g_return_if_fail (error == NULL || *error == NULL);
klass = VIEWER_FILE_GET_CLASS (self);
/* if the method is purely virtual, then it is a good idea to
* check that it has been overridden before calling it, and,
* depending on the intent of the class, either ignore it silently
* or warn the user.
*/
g_return_if_fail (klass->open != NULL);
klass->open (self, error);
}
void
viewer_file_close (ViewerFile *self,
GError **error)
{
ViewerFileClass *klass;
g_return_if_fail (VIEWER_IS_FILE (self));
g_return_if_fail (error == NULL || *error == NULL);
klass = VIEWER_FILE_GET_CLASS (self);
if (klass->close != NULL)
klass->close (self, error);
}
Object的private虚函数
只要在头文件不提供调用虚函数指针的public方法就可以了,比如去掉上面代码头文件里的void viewer_file_close(ViewerFile *self, GError **error);
函数定义,然后在源文件的函数实现前面加上static
关键字限制函数作用域为当前文件即可。