在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); }