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;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值