一、类和对象
1、类:是一种用户自定义的数据类型,也称为类类型(结构体)
2、对象:类的一种具象
//模型
struct Animal //类
{
int age; //成员属性
int sex;
void (*peat)(); //成员方法
void (*pbeat)();
}
void dogEat()
{
;
}
void dogbeat()
{
;
}
方法一:
int main()
{
struct Animal dog; //对象
dog.peat = dogEat; //应用方式
dog.pbeat = dogbeat;
dog.peat(); //调用函数方法
dog.pbeat();
}
方法二:
int main()
{
struct Animal dog = {
.peat = dogEat;
.pbeat = dogpbeat;
};
dog.peat(); //调用函数
dog.pbeat();
}
Animal.h
cat.c
dog.c
person.c
findname.c
main.c
#include <stdio.h>
#include <string.h>
struct Animal //类
{
char name[64];
int age; //成员属性
char sex[128];
void (*peat)(); //成员方法
void (*pbeat)();
struct Animal * next;
};
struct Animal * putdogInLink(struct Animal * head);
struct Animal * putCatInLink(struct Animal * head);
struct Animal * putpersonInLink(struct Animal * head);
struct Animal * FindName(char *name,struct Animal * head);
//用头插法创建链表
//cat
#include "Animal.h"
void catEat()
{
printf("cat eat fish\n");
}
void catbeat()
{
printf("tickle your dick\n");
}
struct Animal cat = {
.name = "Garfield",
.peat = catEat,
.pbeat = catbeat
};
struct Animal * putCatInLink(struct Animal * head)
{
if(head == NULL)
{
head = &cat;
return head;
}
else
{
cat.next = head;
head = &cat;
}
return head;
}
//用头插法创建链表
//dog
#include "Animal.h"
void dogEat()
{
printf("dogs eat turds\n");
}
void dogbeat()
{
printf("Bite your dick\n");
}
struct Animal dog = {
.name = "Odie",
.peat = dogEat,
.pbeat = dogbeat
};
struct Animal * putdogInLink(struct Animal * head)
{
if(head == NULL)
{
head = &dog;
return head;
}
else
{
dog.next = head;
head = &dog;
}
return head;
}
//用头插法创建链表
//person
#include "Animal.h"
void personEat()
{
printf("person eat rich\n");
}
void personbeat()
{
printf("pull your dick\n");
}
struct Animal person = {
.name = "Jon",
.peat = personEat,
.pbeat = personbeat
};
struct Animal * putpersonInLink(struct Animal * head)
{
if(head == NULL)
{
head = &person;
return head;
}
else
{
person.next = head;
head = &person;
}
return head;
}
#include "Animal.h"
//查找函数findname
struct Animal * FindName(char *name,struct Animal * head)
{
struct Animal *tmp = head;
if(head == NULL)
{
printf("NULL\n");
return NULL;
}
else
{
while(tmp != NULL)
{
if(strcmp(tmp->name,name) == 0)
{
return tmp;
}
tmp = tmp->next;
}
return NULL;
}
}
#include "Animal.h"
//main
int main()
{
char buf[128] = {"\0"};
struct Animal *tmp;
struct Animal * head = NULL; //实现链表
head = putdogInLink(head);
head = putCatInLink(head);
head = putpersonInLink(head);
printf("please input Odie、Jon、Garfield\n");
scanf("%s",buf);
while(1)
{
tmp = FindName(buf,head);
if(tmp != NULL)
{
tmp->peat(); //调用相应名字下的功能
tmp->pbeat();
}
memset(buf,'\0',sizeof(buf));
}
return 0;
}
文章展示了如何在C语言中模拟类和对象的概念,通过结构体定义Animal类,并使用指针函数实现方法。使用头插法创建和管理一个包含不同动物(如Dog、Cat和Person)的链表,通过链表中的FindName函数查找并执行特定动物的行为方法。

被折叠的 条评论
为什么被折叠?



