c 结构体 & 函数指针模拟实现一个java class(类) 和方法

时间:2023-12-29 16:21:50

闲来无事,纯粹练习。

student.h

#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED #include <memory.h>
#include <stdlib.h> typedef struct _Student
{
char name[]; 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) / ;
} //数学, 语文, 英文加起来的平均分
int avg2(struct _Student *lpSelf)
{
return (lpSelf->sx + lpSelf->yw + lpSelf->yy) / ;
} //初始化
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 = ;
lpStdt->yw = ;
lpStdt->yy = ;
lpStdt->wl = ;
lpStdt->hx = ;
lpStdt->sw = ; printf(" avg:%d\n", lpStdt->avg(lpStdt));
printf("avg2:%d\n", lpStdt->avg2(lpStdt)); return ;
}

输出的结果:

avg:35
avg2:20