1. 程式人生 > >動態對象綁定

動態對象綁定

動態 amp eagle net bird != typedef main urn

參考鏈接: http://www.jb51.net/article/82718.htm

C實現結構體對象的動態綁定

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct bird{
     void (*fly)(void);
     void (*type)(struct bird*);
}BIRD;

typedef struct parrot{
    BIRD obj;
    void (*fly)(void);
}PARROT;

typedef struct
eagle { int type; BIRD obj; void (*fly)(void); }EAGLE; void parrot_type(struct bird *bird) { struct parrot *parrot = (struct parrot*)((char*)bird-(char*)&(((struct parrot*)0)->obj) ); if(parrot->fly != NULL) { bird->fly = parrot->fly; } } void
fly() { printf("flying\n"); } void eagle_fly(){ printf("eagle fly\n"); } void parrot_fly() { printf("parrot fly\n"); } void init_fly(BIRD *pBird) { memset(pBird,0, sizeof(BIRD)); pBird->fly = fly; } void start_fly(BIRD *pBird) { pBird->type(pBird); pBird->fly(); }
int main(int argc, char const *argv[]) { BIRD bird; init_fly(&bird); PARROT parrot; parrot.fly = parrot_fly; parrot.obj = bird; parrot.obj.type = parrot_type; start_fly(&parrot.obj); return 0; }

動態對象綁定