标签归档:继承

实现C语言的继承和多态

较经典的动物世界中的实例来举例:
假设动物们(包括人)都会吃(Eat),会走(Walk),会说(Talk),而派生类为 dog(汪星人) 和 cat(喵星人),当然还可以是更多,dog 和 cat 都有自己独特的 eat, walk 和 talk 方式,那么大致的代码如下:
代码无警告编译运行

基类头文件

// animal.h
#ifndef ANIMAL_H__
#define ANIMAL_H__

typedef struct animal_s_ animal_t;
typedef struct animal_ops_s_ animal_ops_t;

struct animal_s_ {
        char *name;
        animal_ops_t *animal_ops;
};

struct animal_ops_s_ {
        void (*eat)(char *);
        void (*walk)(int);
        void (*talk)(char *);
};

animal_t *animal_init(char *name);

void animal_eat(animal_t *, char *food);
void animal_walk(animal_t *, int steps);
void animal_talk(animal_t *, char *msg);

void animal_die(animal_t *);

#endif//ANIMAL_H__

基类实现

// animal.c
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "animal.h"

animal_t *animal_init(char *name)
{
        assert(name != NULL);
        size_t name_len = strlen(name);

        animal_t *animal = malloc(sizeof (*animal)
                + sizeof (animal_ops_t) + name_len + 1);
        memset(animal, 0, sizeof (*animal)
                + sizeof (animal_ops_t) + name_len + 1);
        animal->name = (char *)animal
                + sizeof (animal_t) + sizeof (animal_ops_t);
        memcpy(animal->name, name, name_len);
        animal->animal_ops = (animal_ops_t *)((char *)animal
                + sizeof (*animal));

        return animal;
}

void animal_eat(animal_t *animal, char *food)
{
        animal->animal_ops->eat(food);

        return;
}

void animal_walk(animal_t *animal, int steps)
{
        animal->animal_ops->walk(steps);

        return;
}

void animal_talk(animal_t *animal, char *msg)
{
        animal->animal_ops->talk(msg);

        return;
}

void animal_die(animal_t *animal)
{
        assert(animal != NULL);
        free(animal);

        return;
}

继续阅读