码迷,mamicode.com
首页 > 其他好文 > 详细

动态对象绑定

时间:2018-01-22 16:06:37      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:struct   pos   obj   art   eagle   init   blog   argc   参考   

参考链接:  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;
}

 

动态对象绑定

标签:struct   pos   obj   art   eagle   init   blog   argc   参考   

原文地址:https://www.cnblogs.com/hzijone/p/8329248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!