• Glib学习笔记(一)


    你将学到什么

    如何使用GObject实现一个新类

    类头文件

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

    • 不可被继承的类型(Final类型)使用G_DECLARE_FINAL_TYPE宏来定义,还需要在源文件(不是在头文件)中定义一个结构来保存类实例数据。
    /*
     * Copyright/Licensing information.
     */
    
    /* 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宏来定义
    /*
     * Copyright/Licensing information.
     */
    
    /* 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__ */
    

    类源文件

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

    /*
     * Copyright information
     */
    
    #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宏实现的接口。

  • 相关阅读:
    ios开发学习视图切换(View Transition)效果源码分享系列教程
    ios开发学习cocos2d(cocos2d)效果源码分享系列教程
    C++类模板定义放在cpp里报错:LNK2019无法解析的外部符号
    std::string学习
    C++之ODB框架
    C++虚析构函数
    Windows编译GRPC
    Qt信号与槽原理
    GRPC环境配置
    C++传入指针并在内部new失败
  • 原文地址:https://www.cnblogs.com/silvermagic/p/9087886.html
Copyright © 2020-2023  润新知