C WIth Class Designer

来源:互联网 发布:spring入门经典 源码 编辑:程序博客网 时间:2024/06/07 06:47

其实C语言实现C++的封装、多态是比较方便的,主要看你的设计。

class.h header file

#define buf_max 32typedef 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 methodchild *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 methodstatic 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;}
0 0
原创粉丝点击