Created
April 19, 2009 19:53
-
-
Save tj/98193 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #define ALLOC(t) (t *) malloc(sizeof(t)) | |
| typedef unsigned int OBJ; | |
| typedef enum { | |
| tVector, | |
| tPoint | |
| } Type; | |
| // --- Vector | |
| typedef struct _Vector { | |
| int x, y; | |
| Type t; | |
| } *Vector; | |
| inline Vector | |
| Vector_alloc() { | |
| return ALLOC(struct _Vector); | |
| } | |
| OBJ | |
| Vector_new(int x, int y) { | |
| Vector v = Vector_alloc(); | |
| v->x = x; v->y = y; | |
| v->t = tVector; | |
| return (OBJ) v; | |
| } | |
| // --- Point | |
| typedef struct _Point { | |
| int x, y; | |
| Type t; | |
| } *Point; | |
| inline Point | |
| Point_alloc() { | |
| return ALLOC(struct _Point); | |
| } | |
| OBJ | |
| Point_new(int x, int y) { | |
| Point p = Point_alloc(); | |
| p->x = x; p->y = y; | |
| p->t = tPoint; | |
| return (OBJ) p; | |
| } | |
| static void | |
| inspect(Vector self) { | |
| char *type; | |
| switch (self->t) { | |
| case tVector : type = "Vector" ;break; | |
| case tPoint : type = "Point" ;break; | |
| } | |
| printf("<%s x:%d y:%d>\n", type, self->x, self->y); | |
| } | |
| int | |
| main(int argc, char **argv) | |
| { | |
| OBJ a = Vector_new(10, 20); | |
| inspect(a); | |
| OBJ b = Point_new(30, 40); | |
| inspect(b); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment