初识面向对象编程 Object Oriented Programming
今天初次接触了面向对象编程。 面向对象编程是一个核心思想,不是一个编程技术。我们要主要观点就是对程序实现的设计。 先不关心每一个function如何实现,先设计出了整个程序的框架。
我们先定义需要用到的struct或者class。在根据我们的设计和需求写出需要用的function。 在设计function的时候记得要写明程序的接口。即function调用的变量。 但是暂时先不用写function的内容。 这些东西都是放在头文件里。头文件里可以不用#include不必要的东西,这些在cpp文件里声明就好。
例子
这里我们先写一个和之前类似的code。目的是建立一个学生档案的数据库。允许创建一个数据,这个数据是一个有头的链表,它串联所有的学生信息。我们可以通过学生的id来检索到学生。
其中我们要写的函数有 创建数据 删除数据 加入元素(每个学生) 删除元素 其中插入的学生应该按照id的编号 从小到大排列好。
学生的数据我们可以再main函数里直接写入 也可以用cout或者sscanf来定义一个变量让用户输入。
下面是code
cpp文件
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include "DataStore.h"// 记得在这里include头文件
using namespace std;
DataStore* ds_create() {
//创建一个空间
DataStore* store = (DataStore*)malloc(sizeof(DataStore));
//初始化
store->head.next = 0;
return store;
}
void ds_destroy(DataStore* store) {
//释放空间
Student* p = store->head.next;
while (p) {
Student* next = p->next;
free(p);
p = p->next;
}
free(store);
}
void show_all(DataStore* store) {
//遍历链表并输出
Student* p = store->head.next;
while (p) {
cout << "ID:" << p->id << endl;
cout << "name;" << p->name << endl;
p = p->next;
}
}
void ds_add(DataStore* store, const Student* data) {
//按照id的顺序把新的student添加进链表
Student* copy = (Student*)malloc(sizeof(Student));
*copy = *data; //不知道这里为什么有提示: 1个重载
Student* cur = store->head.next; //初始化 cur 指向链表头的下一个
Student* pre = &store->head; // 初始化 pre 是链表头的地址
while (cur) {
if ( copy->id < cur->id) {
//找到符合条件的id 之后break 这是cur指向插入位置的下一个,pre指向插入位置的上一个。
break;
}
pre = cur;
cur = cur->next;
}
copy->next = cur; //让copy的next 指向 插入位置的下一个
pre->next = copy;// 让插入位置的上一个next 指向copy的地址
}
//Student* ds_find();
头文件
//头文件可以不用include东西 在cpp文件里include就可以
struct Student
{
int id;
char name[16];
Student* next;
};
struct DataStore
{
Student head;
};
//定义各种函数(要包涵端口)
DataStore* ds_create();
void ds_destroy(DataStore* store);
void show_all(DataStore* store);
void ds_add(DataStore* store, const Student* data);
main function
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include "DataStore.h"
using namespace std;
int main() {
DataStore* store= ds_create();
Student s;
s.id = 1;
strcpy(s.name, "eric");
ds_add(store, &s);
s.id = 2;
strcpy(s.name, "tim");
ds_add(store, &s);
s.id = 3;
strcpy(s.name, "frank");
ds_add(store, &s);
s.id = 5;
strcpy(s.name, "tom");
ds_add(store, &s);
s.id = 4;
strcpy(s.name, "kim");
ds_add(store, &s);
show_all( store);
return 0;
}```