如何实现面向对象编程?
第一步:假设存在一个对象,设想可以为它提供什么服务
第二步:定义如何使用它的服务,细化为函数。
第三步:选择一种实现方法,写代码实现上面的接口。
//以下是一个代码事例
//DataStore.h
struct Student
{
int id;
char name[16];
Student* next;
} ;
struct DataStore
{
Student head;
};
DataStore* ds_create();
void ds_destroy(DataStore* store);
void ds_add(DataStore* store,Student* data);
//按id查找一个记录
Student* ds_find(DataStore* store,int id);
//按着id删除一个记录
void ds_remove(DataStore* store,int id);
//打印所有的记录
void ds_print(DataStore* store);
//DataStore.cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"DataStore.h"
DataStore* ds_create()
{
DataStore* store = (DataStore*)malloc(sizeof(DataStore));
store->head.next = NULL;
return store;
}
void ds_destroy(DataStore* store)
{
Student* p = store->head.next;
while(p)
{
Student* next = p->next;
free(p);
p = next;
}
free(store);
}
void ds_add(DataStore* store,Student* data)
{
Student* copy = (Student*)malloc(sizeof(Student));
*copy = *data;
Student* cur = store->head.next;
Student* pre = &store->head;
while(cur)
{
if(copy->id < cur->id)
{
break;
}
pre = cur;
cur = cur->next;
}
copy->next = pre->next;
pre->next = copy;
}
//按id查找一个记录
Student* ds_find(DataStore* store,int id)
{
return NULL;
}
//按着id删除一个记录
void ds_remove(DataStore* store,int id)
{
}
//打印所有的记录
void ds_print(DataStore* store)
{
Student* p = store->head.next;
while(p)
{
printf("id = %d , name = %s \n",p->id,p->name);
p = p->next;
}
}
//DataStoreMAIN.cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"DataStore.h"
int main()
{
DataStore* store = ds_create();
Student s;
s.id = 17;
strcpy(s.name,"xiaoming");
ds_add(store,&s);
s.id = 31;
strcpy(s.name,"xiaowei");
ds_add(store,&s);
ds_print(store);
ds_destroy(store);
return 0;
}