c 结构体 & 函数指针模拟实现一个java class(类) 和方法
闲来无事,纯粹练习。
student.h
#ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED #include <memory.h> #include <stdlib.h> typedef struct _Student { char name[16]; int sx; //数学 int yw; //语文 int yy; //英语 int wl; //物理 int hx; //化学 int sw; //生物 int (*avg)(struct _Student *); // 所有分数的加起来的平均分 int (*avg2)(struct _Student *); //数学, 语文, 英文加起来的平均分 } Student, *lpStudent; Student *student_init(); //初始化 #endif // STUDENT_H_INCLUDED
student.c
#include "student.h" // 所有分数的加起来的平均分 int avg(struct _Student *lpSelf) { return (lpSelf->sx + lpSelf->yw + lpSelf->yy + lpSelf->wl + lpSelf->hx + lpSelf->sw) / 6; } //数学, 语文, 英文加起来的平均分 int avg2(struct _Student *lpSelf) { return (lpSelf->sx + lpSelf->yw + lpSelf->yy) / 3; } //初始化 Student *student_init() { lpStudent lpStdt = (lpStudent) malloc(sizeof(Student)); memset(lpStdt, '\0', sizeof(Student)); lpStdt->avg = avg; lpStdt->avg2 = avg2; return lpStdt; }
test.c
int main(int argc, char *argv[]) { Student *lpStdt = student_init(); lpStdt->sx = 10; lpStdt->yw = 20; lpStdt->yy = 30; lpStdt->wl = 40; lpStdt->hx = 50; lpStdt->sw = 60; printf(" avg:%d\n", lpStdt->avg(lpStdt)); printf("avg2:%d\n", lpStdt->avg2(lpStdt)); return 0; }
输出的结果:
avg:35
avg2:20