相关文章推荐
鼻子大的煎饼果子  ·  Android ...·  2 周前    · 
胆小的鼠标  ·  c# ...·  1 年前    · 
大方的沙发  ·  C# Entity FrameWork ...·  1 年前    · 

声明一个类型的方法选择取决于类型是可被继承的还是不可被继承的。

  • 不可被继承的类型(Final类型)使用 G_DECLARE_FINAL_TYPE 宏来定义,还需要在源文件(不是在头文件)中定义一个结构来保存类实例数据。
  • /* inclusion guard */ #ifndef __VIEWER_FILE_H__ #define __VIEWER_FILE_H__ #include <glib-object.h> * Potentially, include other headers on which this header depends. G_BEGIN_DECLS * Type declaration. #define VIEWER_TYPE_FILE viewer_file_get_type () G_DECLARE_FINAL_TYPE (ViewerFile, viewer_file, VIEWER, FILE, GObject) * Method definitions. ViewerFile *viewer_file_new (void); G_END_DECLS #endif /* __VIEWER_FILE_H__ */
  • 可被继承的类型使用 G_DECLARE_DERIVABLE_TYPE 宏来定义
  • /* inclusion guard */ #ifndef __VIEWER_FILE_H__ #define __VIEWER_FILE_H__ #include <glib-object.h> * Potentially, include other headers on which this header depends. G_BEGIN_DECLS * Type declaration. #define VIEWER_TYPE_FILE viewer_file_get_type () G_DECLARE_DERIVABLE_TYPE (ViewerFile, viewer_file, VIEWER, FILE, GObject) struct _ViewerFileClass GObjectClass parent_class; /* Class virtual function fields. */ void (* open) (ViewerFile *file, GError **error); /* Padding to allow adding up to 12 new virtual functions without * breaking ABI. */ gpointer padding[12]; * Method definitions. ViewerFile *viewer_file_new (void); G_END_DECLS #endif /* __VIEWER_FILE_H__ */

    源文件第一步就是包含上面的头文件

    #include "viewer-file.h" /* Private structure definition. */ typedef struct { gchar *filename; /* stuff */ } ViewerFilePrivate; * forward definitions

    如果定义的是不可继承类型,还需要定义类实例数据结构

    struct _ViewerFile
      GObject parent_instance;
      /* Other members, including private data. */
    

    调用G_DEFINE_TYPE将会:

  • 实现viewer_file_get_type函数
  • 定义了一个能在源文件范围内访问父类的指针
  • 使用G_DEFINE_TYPE_WITH_PRIVATE宏添加私有的实例数据到类型上
  • 如果定义的是不可继承类型,使用G_DECLARE_FINAL_TYPE将私有数据存放在实例结构中,实例结构外部无法访问,也不会被其他类继承(因为定义的是不可继承类型)。
    你也可以使用G_DEFINE_TYPE_WITH_CODE宏来控制get_type函数的实现,例如插入一个G_IMPLEMENT_INTERFACE宏实现的接口。