강좌 & 팁
글 수 2,412
2015.09.15 18:45:23 (*.39.166.80)
82579
gxlib을 만져보던 중에 어떻게 하면 오브젝트를 편하게 그릴 수 있을까 고민하다 이러면 어떨까 생각해봤습니다.
struct object {
int x;
int y;
void (*report)( struct object *);
void (*move)( struct object *, int, int);
};우선 사용할 객체입니다. 그리고 저 안에 있는 함수 포인터에 넣고 싶은 메소드를 넣습니다.
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;
}그리고 이제 사용합니다.
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로도 객체 지향 언어를 어설프게나마 흉내낼 수 있게 됩니다.

