C语言实现继承与多态的代码

代码语言:c

所属分类:其他

代码描述:C语言实现继承与多态的代码,利用struct

代码标签: 继承 多态

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#include <stdio.h>
#include <stdlib.h>
 
//虚函数表结构
struct base_vtbl
{
    void(*dance)(void *);
    void(*jump)(void *);
};
 
//基类
struct base
{
    /*virtual table*/
    struct base_vtbl *vptr;
};
 
void base_dance(void *this)
{
    printf("base dance\n");
}
 
void base_jump(void *this)
{
    printf("base jump\n");
}
 
/* global vtable for base */
struct base_vtbl base_table =
{
        base_dance,
        base_jump
};
 
//基类的构造函数
struct base * new_base()
{
    struct base *temp = (struct base *)malloc(sizeof(struct base));
    temp->vptr = &base_table;
    return temp;
}
 
 
//派生类
struct derived1
{
    struct base super;
    /*derived members */
    int high;
};
 
void derived1_dance(void * this)
{
    /*implementation of derived1's dance function */
    printf("derived1 dance\n");
}
 
void derived1_jump(void * this)
{
    /*implementation of derived1's jump function */
    struct derived1*.........完整代码请登录后点击上方下载按钮下载查看

网友评论0