C++结构体实现面向对象


#include <stdio.h>
#include <string.h>
#include <stdlib.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, const Student* data)
{
	// 创建对象、复制数据
	Student* copy = (Student*)malloc(sizeof(Student));
	*copy = *data;

	// 插入一个对象到链表中
	Student* cur = store->head.next; // 当前节点current
	Student* pre = &store->head;  // 上一个节点previous
	while(cur)
	{		
		if(copy->id < cur->id) // 找到这个位置
			break;

		pre = cur;
		cur = cur->next;  // 找到最后一个对象
	}

	// 插入到pre节点的后面
	copy->next = pre->next;
	pre->next = copy;

}


// (2) 可以按ID来查找一个记录
Student* ds_find(DataStore* store, int id)
{
	Student* p = store->head.next; 
	while(p)
	{
		if(p->id == id)
			return p;

		p = p->next; // 下一个对象
	}
	return NULL;
}

//(3) 可以按ID删除一个记录
void ds_remove(DataStore* store, int id)
{

}

// (4) 可以打印显示所有的记录
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; // 下一个对象
	}
}

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "DataStore.h"

int main()
{
	DataStore* store = ds_create();

	Student s;
	s.id = 1;
	strcpy(s.name, "111");
	ds_add(store, &s);

	s.id = 2;
	strcpy(s.name, "222");
	ds_add(store, &s);

	Student* f = ds_find(store, 2);

	ds_print(store);

	ds_destroy(store);

	return 0;
}


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, const Student* data);

Student* ds_find(DataStore* store, int id);

void ds_remove(DataStore* store, int id);

void ds_print(DataStore* store);

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值