C语言实现继承和多态

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/susidian/article/details/51069187
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

//-------------  Person  --------------
typedef struct Person {
    void* derived_obj;
    char* name;
    void (*life)(struct Person*);
    void (*live)(struct Person*);
    void (*delete)(struct Person*);
} Person;

void Person_life(Person* p) {
    printf("As a person, I'm %s, the life is colorfull\n", p->name);
}

void Person_live(Person* p) {
    printf("As a person, I'm %s, I'd like to live in city\n", p->name);
}

void delete_Person(Person* p) {
    free(p->name);
    free(p);
}

Person* new_Person(const char* name) {
    Person* p = (Person*)malloc(sizeof(Person));
    int name_len = (int)strlen(name) + 1;
    p->name = (char*)malloc(name_len);
    p->life = Person_life;
    p->live = Person_live;
    p->derived_obj = NULL;
    p->delete = delete_Person;
    memcpy(p->name, name, name_len);
    return p;
}

//-------------  Employee  --------------
typedef struct Employee {
    Person* base_obj;
    int id;
    void (*work)(struct Person*);
} Employee;

void Employee_live(Person* p) {
    printf("As an employee(id:%d), I'm %s, I'd like to live near by company\n", ((Employee*)p->derived_obj)->id, p->name);
}

void Employee_work(Person* p) {
    printf("As an employee(id:%d), I'm %s, I'll try my best to work\n", ((Employee*)p->derived_obj)->id, p->name);
}

void delete_Employee(Person* p) {
    Employee* e = (Employee*)p->derived_obj;
    delete_Person(p);
    free(e);
}

Employee* new_Employee(const char* name, int id) {
    Employee* e = (Employee*)malloc(sizeof(Employee));
    e->base_obj = new_Person(name);
    e->base_obj->derived_obj = e;
    e->base_obj->delete = delete_Employee;

    e->base_obj->live = Employee_live;

    e->id = id;
    e->work = Employee_work;
    return e;
}

#define DYNAMIC_CAST(p, TYPE) ((TYPE*)p->derived_obj)
#define STATIC_CAST(p, TYPE) ((TYPE*)p->base_obj)

int main(int argc, const char* argv[]) {
    Person* p = new_Person("bacoo");
    Person* e = STATIC_CAST(new_Employee("lily", 33), Person);

    printf("\n------ Person ------\n");
    p->life(p);
    p->live(p);

    printf("\n------ Employee ------\n");
    e->life(e); //inherit Person::life
    e->live(e); //override Person::live
    DYNAMIC_CAST(e, Employee)->work(e); //new method Employee::work

    p->delete(p);
    e->delete(e);
    return 0;
}

 

展开阅读全文

没有更多推荐了,返回首页