gxlib을 만져보던 중에 어떻게 하면 오브젝트를 편하게 그릴 수 있을까 고민하다 이러면 어떨까 생각해봤습니다.


1
2
3
4
5
6
7
struct object {
    int x;
    int y;
     
    void (*report)( struct object *);
    void (*move)( struct object *, int, int);
};

우선 사용할 객체입니다. 그리고 저 안에 있는 함수 포인터에 넣고 싶은 메소드를 넣습니다.

1
2
3
4
5
6
7
8
9
10
void on_report_honestly( struct object *object) {
    printf("I'm on ( %d, %d)!\n", object->x, object->y);
}
void on_report_insincerely( struct object *object) {
    printf("I'm not on ( %d, %d)!\n", object->x, object->y);
}
void on_move( struct object *object, int x, int y) {
    object->x = x;
    object->y = y;
}

그리고 이제 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct object *make_trueman() {
    struct object *object = (struct object *) malloc( sizeof( struct object));
    memset( object, 0, sizeof( struct object));
     
    object->report = on_report_honestly;
    object->move = on_move;
 
    return object;
}
 
struct object *make_lier() {
    struct object *object = (struct object *) malloc( sizeof( struct object));
    memset( object, 0, sizeof( struct object));
     
    object->report = on_report_insincerely;
    object->move = on_move;
 
    return object;
}
 
int main( void) {
    struct object *object = make_trueman();
    object->move( object, 1, 2);
    object->report( object);
 
    struct object *object = make_lier();
    object->move( object, 1, 2);
    object->report( object);
 
    return 0;
}
이렇게 하면 C로도 객체 지향 언어를 어설프게나마 흉내낼 수 있게 됩니다.