面向对象,什么是对象?
对象就是有自己的实体,有自己的动作。
对于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。