黑马程序员技术交流社区
标题:
其实C使用结构体也能跟OC一样用面向对象思想编程
[打印本页]
作者:
talent123
时间:
2015-6-5 23:23
标题:
其实C使用结构体也能跟OC一样用面向对象思想编程
结构体跟类有很多共同之处
当然可能类 更简便一些。
这是我自己写的程序
单独写一个set和get方法 就可以当做类来使用了
#include <stdio.h>
typedef struct{
int no;
char name[20];
int score[3];
}Student;
typedef struct{
Student stu1;
Student stu2;
Student stu3;
Student stu4;
Student stu5;
Student stu6;
Student stu7;
Student stu8;
Student stu9;
Student stu10;
}Students;
//Student stu;
//Student *pStudent=&stu;
Student * student_input(Student *pStudent);
void student_print(const Student *pStudent);
double student_average(const Student *pStudent);
int student_get_score(const Student *pStudent, int index);
double students_average(const Students *pstudents);
int main (int argc, char const *argv[])
{
int average=0.0;
Student stu={0,"",{0,0,0}};
student_input(&stu);
average=student_average(&stu);
student_print(&stu);
return 0;
}
Student * student_input(Student *pStudent){
scanf ("%d %s %d %d %d",&pStudent->no,&pStudent->name,
&pStudent->score[0],&pStudent->score[1],&pStudent->score[2]);
return pStudent;
}
void student_print(const Student *pStudent){
double average ;
average=(pStudent->score[0]+pStudent->score[1]+pStudent->score[2])/3.0;
printf ("%d\t%s\t%d\t%d\t%d\t%f\n",pStudent->no,pStudent->name,
pStudent->score[0],pStudent->score[1],pStudent->score[2],average);
}
double student_average(const Student *pStudent){
double average=0.0;
average=(pStudent->score[0]+pStudent->score[1]+pStudent->score[2])/3.0;
return average;
}
int student_get_score(const Student *pStudent, int index){
int a=0;
a=pStudent->score[index];
return a;
}
double students_average(const Students *pstudents,int index){
double students_average;
students_average=(pstudents->stu1.score[index]+pstudents->stu2.score[index]+pstudents->stu3.score[index]+pstudents->stu4.score[index]+pstudents->stu5.score[index]+pstudents->stu6.score[index]+pstudents->stu7.score[index]+pstudents->stu8.score[index]+pstudents->stu9.score[index]+pstudents->stu10.score[index])/10.0;
return students_average;
}
void max_score(const Student *pstudent,int index ){
int max_score=0;
int i
for (i=1;i<=10;i++){
if (max_score<=*pstudent->score[index]){
max_score=*pstudent->score[index];
}
pstudent++;
}
printf("%d",max_score);
}
复制代码
作者:
Elors
时间:
2015-6-6 09:13
因为面向对象是建立在面向过的基础上的。
作者:
张晓珊
时间:
2015-6-6 09:54
OC的本质就是把C给封装了啊,底层还是面向对象的啊!
作者:
任伟
时间:
2015-6-6 09:59
学习了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2