如何让c语言使用结构体近似模拟c++中的类
如今统治市场的主流编程语言,如c++,java,大都是面向对象类型的编程语言。
而众所周知,c语言是面向过程的编程语言,但是它拥有一个类似于类的结构,叫做结构体,主要的区别在于结构体无法定义函数。
因此,为了c语言的结构体近似模拟类,我们可以在结构体中定义函数指针。
下面这个例子,是最常用的计算学生分数平均数的c++类模版:
#include #include #include #define LINE for (i = 0 ; i < 60 ; i++) {printf("-");}printf("\n");#define SPACE for (i = 0 ; i < 20 ; i++) printf(" ");using namespace std;class Student{public: double stuAvg(double score[]); int num; char name[10]; double score[3]; double average;};double Student::stuAvg(double score[]){ double sum = 0.0; double average = 0.0; for (int i=0 ; i < 3 ; i++) { sum += score[i]; } return average = sum/3;}int main(void){ Student stu1; for (int i = 0 ; i < 3 ; i++) { scanf("%lf",&stu1.score[i]); } stu1.num = 1001; memset(stu1.name,0,sizeof(stu1.name)); strcat(stu1.name,"Peter"); stu1.average = stu1.stuAvg(stu1.score); //Output Part printf("NUM"); SPACE; printf("NAME"); SPACE; printf("AVERAGE"); printf("\n"); LINE; printf("%d",stu1.num); SPACE; printf("%s",stu1.name); SPACE; printf("%.2lf",stu1.average); printf("\n"); LINE; return 0;}
接下来我们使用结构体模拟上例中类的作用:
#include #include #define LINE for (i = 0 ; i < 60 ; i++) {printf("-");}printf("\n"); #define SPACE for (i = 0 ; i < 20 ; i++) printf(" "); struct Student{ double (*stuAvg)(double score[]); int num; char name[10]; double score[3]; double average; }; double Calc_Avg(double score[]){ int i = 0; double sum = 0.0; double average = 0.0; for (i=0 ; i < 3 ; i++) { sum += score[i]; } return average = sum/3; } void main(void){ int i = 0; struct Student stu1; for (i = 0 ; i < 3 ; i++) { scanf("%lf",&stu1.score[i]); } stu1.num = 1001; memset(stu1.name,0,sizeof(stu1.name)); strcat(stu1.name,"Peter"); stu1.stuAvg = Calc_Avg; stu1.average = stu1.stuAvg(stu1.score); //Ouuput Part printf("NUM"); SPACE; printf("NAME"); SPACE; printf("AVERAGE"); printf("\n"); LINE; printf("%d",stu1.num); SPACE; printf("%s",stu1.name); SPACE; printf("%.2lf",stu1.average); printf("\n"); LINE; return; }
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~