//定义一个基类 Object //注意这里使用了函数指针,从而可以实现函数重载 typedefstruct { char *description; int (*init)(void *self); void (*describe)(void *self); void (*destroy)(void *self); void *(*move)(void *self, Direction direction); int (*attack)(void *self, int damage); } Object;
//基类的构造函数 void *Object_new(size_t size, Object proto, char *description) { // setup the default functions in case they aren't set if(!proto.init) proto.init = Object_init; if(!proto.describe) proto.describe = Object_describe; if(!proto.destroy) proto.destroy = Object_destroy; if(!proto.attack) proto.attack = Object_attack; if(!proto.move) proto.move = Object_move;
// this seems weird, but we can make a struct of one size, // then point a different pointer at it to "cast" it Object *el = calloc(1, size); *el = proto;
// copy the description over el->description = strdup(description);
// initialize it with whatever init we were given if(!el->init(el)) { // looks like it didn't initialize properly el->destroy(el); returnNULL; } else { // all done, we made an object of any type return el; } }