c语言实现面向对象编程

面向对象,什么是对象?
对象就是有自己的实体,有自己的动作。

对于c语言来说结构体,一般来说只是存储数据,相当于有了实体,但是没有动作。也没有手脚,走不了路.那么我们就给这个结构体,创造手脚,教他走路。这样就实现了面向对象编程

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
//给它手脚
typedef struct Person
{
    char * hand;
    char * foot;
    char * head;
    void (*init)(struct Person * p);
    void (*deinit)(struct Person * p);
    int (*handshake)(struct Person * p);
    int (*walk)(struct Person * p);
    int (*shankehead)(struct Person * p);
}Per;

//教他走路,握手
void Person_init(Per * p)
{
    assert(p != NULL);
    p->hand = malloc(10);
    assert(p->hand != NULL);
    p->foot = malloc(10);
    assert(p->foot != NULL);
    p->head = malloc(10);
    assert(p->head != NULL);
}

void Person_deinit(Per * p)
{
    assert(p != NULL);
    if(p->hand){ free(p->hand); p->hand = NULL;};
    if(p->foot){ free(p->foot); p->foot = NULL;};
    if(p->head){ free(p->head); p->head = NULL;};
}

//握手
int Person_ShankeHand(Per * p)
{
    memcpy(p->hand,"握手",10);
    printf("hand is %s\n",p->hand);
}

//走路
int Person_Walk(Per * p)
{
    memcpy(p->foot,"走路",10);
    printf("foot is %s\n",p->foot);
}

//摇头
int Person_ShankeHead(Per * p)
{
    memcpy(p->head,"摇头",10);
    printf("head is %s\n",p->head);
}

int main()
{
    Per * per1 = malloc(sizeof(Per));
    per1->init = Person_init;
    per1->deinit = Person_deinit;
    per1->handshake = Person_ShankeHand;
    per1->walk = Person_Walk;
    per1->shankehead = Person_ShankeHead;

    //现在给它一个手脚
    per1->init(per1);

    //握手
    per1->handshake(per1);

    //走路
    per1->walk(per1);

    //摇头
    per1->shankehead(per1);

    //结束这个人
    per1->deinit(per1);
}
执行结果:
hand is 握手
foot is 走路
head is 摇头

后面再和大家讨论如何实现,c++中的容器,map,等等使用c。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值