天天看點

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

繼續閱讀