在C语言中使用面向对象
参考:
https://blog.csdn.net/daheiantian/article/details/6233058
https://blog.csdn.net/qq_35433716/article/details/87464502
之前一直以为C语言是面向过程的语言,没办法使用面向对象,后来看了大牛的一篇文章。醍醐灌顶,原来面向过程、面向对象是一种编程思想。
C语言只是没有class关键字,并不代表它不能实现面向对象的思想。
下面通过结构体和函数指针定义一个学生Student对象,代码如下:
可以看到,有父类有子类,有属性有方法,基本上已经满足了面向对象的基本要素
/** * Created by wangbin on 2022/1/11. * Implementing Object Orientation in C Language */ #include <stdio.h> //parent class typedef struct PERSON { char *name; int age; } person; //define subclass typedef struct STUDENT { person p; int language; int math; int english; int (*total_score)(struct STUDENT *s); } Student; int get_total_score(struct STUDENT *s) { return s->language + s->math + s->english; } //initial Student void init(Student *s, char *name, int language, int math, int english) { s->p.name = name; s->p.age = 18; s->language = language; s->math = math; s->english = english; s->total_score = get_total_score; } int main(void) { char name[10]; int language, math, english, score1; Student s1; printf("Enter your name and three numbers,split by space\n"); scanf("%s %d %d %d", name, &language, &math, &english); init(&s1, name, language, math, english); score1 = s1.total_score(&s1); printf("name=%s,age=%d,score=%d", s1.p.name, s1.p.age, score1); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
2021-01-11 hive只扫描一遍表实现查询不同条件的数据