C WIth Class Designer

其實C語言實現C++的封裝、多態是比較方便的,主要看你的設計。

class.h header file

#define buf_max 32
typedef struct _parent{
    //define member of superclass
    int  age;
    char name[buf_max];
    char job[buf_max];
    //public method of superclass
    void (*parent_do_work)();
}parent;

typedef struct _child {
    //extend inherit from parent
    struct _parent  *parent;
    //member 
    int age;

    void (*child_do_work)();
}child;
//---parent method---
parent *new_parent();
static void parent_do_work();

//child method
child *new_child();
static void child_do_work();

class.c implement that defined int class.h

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "class.h"
parent *new_parent()
{
    parent *p = (parent *)malloc(sizeof(*p));
    if(p == NULL){
        return NULL;
    }
    //init a super class member 
    p->parent_do_work = &parent_do_work;
    return p;
}
child *new_child() {
    child *ci = (child *)malloc(sizeof(*ci));
    if(ci == NULL){
        return NULL;
    }
    //method init 
    ci->child_do_work = &child_do_work;
    return ci;
}

//parent method 
static void parent_do_work()
{
    fprintf(stdout,"    --parent_do_work:parent is a programmer of c language\n");
}

//child method
static void child_do_work()
{
    fprintf(stdout,"    --child_do_wrok:child is a mysql dba\n");
}
int main(void){
    parent *p = new_parent();
    child *ci = new_child();

    memset(p->name,'\0',buf_max);
    memset(p->job,'\0',buf_max);

    strncpy(p->name,"lest",buf_max);
    strncpy(p->job,"programmer",buf_max);
    p->age = 60;

    ci->parent = p;
    ci->age = 20;

    fprintf(stdout,"-----parent info------\n");
    fprintf(stdout,"    -- parent name =%s\n",p->name);
    fprintf(stdout,"    -- parent age  =%d\n",p->age);
    fprintf(stdout,"    -- parent job  =%s\n",p->job);
    p->parent_do_work();

    fprintf(stdout,"-----child info------\n");
    fprintf(stdout,"    -- child age  =%d\n",ci->age);
    ci->child_do_work();
    ci->parent->parent_do_work();
    free(p);
    free(ci);
    p = NULL;
    ci = NULL;
    return 0;
}
發佈了66 篇原創文章 · 獲贊 18 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章