其实也说不上原理,只是定义一个简单的类来初学。C面向对象是通过模拟实现的,所谓的一个类其实就是两个的结构体。属性就是变量的值或者指针,方法就是函数指针了。更为复杂的事暂时不去考虑,考虑了我也不懂。
#ifndef GO_HELLO_H
#define GO_HELLO_H
#include
#define GO_TYPE_HELLO (go_hello_get_type())
typedef struct _GoHello GoHello;
struct _GoHello {
GObject parent;
int a;
void (*test)(void);
};
typedef struct _GoHelloClass GoHelloClass;
struct _GoHelloClass {
GObjectClass parent_class;
};
GType go_hello_get_type(void);
#endif
我写程序从来不写注释的哈~啊哈哈:)。至于为什么这么写,这么定义,我很明确的说,不知道!反正就这样子做就对了,老问这么多为什么没事找事。
#include "go-hello.h"
G_DEFINE_TYPE(GoHello, go_hello, G_TYPE_OBJECT);
static void go_hello_test(void);
static
void go_hello_init(GoHello *self)
{
g_printf("go hello init!\n");
self->a = NULL;
self->test = go_hello_test;
}
static
void go_hello_class_init(GoHelloClass *klass)
{
g_printf("go hello class init!\n");
}
static
void go_hello_test(void)
{
g_printf("I LOVE YOU CJ!\n");
}
依然没有注释,要注意的就是G_DEFINE_TYPE的第二个参数是指的方法名的前缀。其它三个函数如其字面意思,两个初始化,一个实例方法。
#include "go-hello.h"
int main(int argc, char *argv[])
{
g_type_init();
gohello *hello;
gohello *hello2;
hello = g_object_new(go_type_hello, null);
hello->a = 1;
hello->test();
g_printf("hello->a=%d\n",hello->a);
hello2 = g_object_new(go_type_hello, null);
hello2->test();
return 0;
}
用 gcc `pkg-config --cflags --libs gobject-2.0` go-hello.c main.c -o test
编译
输出结果
ef>./test
go hello class init!
go hello init!
I LOVE YOU CJ!
hello->a=1
go hello init!
I LOVE YOU CJ!
ef>
没啥要注意的,要注意的就是类结构体只初始化了一次。这说明所有对象都是共享类结构体的。所以,如果是类的公共属性什么的,可以放到类结构体里~
It’s all my fault.