C++类实现面向对象

#include "DataStore.h"
#include<stdlib.h>
#include<stdio.h>

DataStore::DataStore() {
	m_head.next = NULL;
}

DataStore::~DataStore() {
	Student* p = m_head.next;
	while (p) {
		Student* next = p->next;
		free(p);
		p = next;
	}
}

void DataStore::Add(const Student* data) {
	Student* copy = (Student*)malloc(sizeof(Student));
	*copy = *data;
	Student* cur = m_head.next;
	Student* pre = &m_head;
	while (cur) {
		if (copy->id < cur->id)
			break;
		pre = cur;
		cur = cur->next;
	}
	copy->next = pre->next;
	pre->next = copy;
}

Student* DataStore::Find(int id) {
	Student* p = m_head.next;
	while (p) {
		if (p->id == id)
			return p;
		p = p->next;
	}
	return NULL;
}

void DataStore::Print() {
	Student* p = m_head.next;
	while (p) {
		printf("ID:%d,name:%s\n", p->id, p->name);
		p = p->next;
	}
}

struct Student {
	int id;
	char name[32];
	Student* next;
};
class DataStore {
public:
	DataStore();
	~DataStore();
public:
	void Add(const Student* data);
	Student* Find(int id);
	void Print();
private:
	Student m_head;
};
#include<stdio.h>
#include<string.h>
#include"DataStore.h"
int main() {
	DataStore store;
	Student stu;
	stu.id = 2018;
	strcpy(stu.name, "2018");
	store.Add(&stu);
	store.Print();

	return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值