1.类的引入
C语言是面向过程的 出一道题:
写一个程序,输出张三,李四两个人的姓名,年龄。
#inlude <stdio.h> int main(int argc,char **argv)//多维数组的地址,行转化列 { char *zs_name = "zhangsan"; int zs_age =10; char *ls_name = "lisi"; int ls_age =10; printf("name = %s,age = %d\n",zs_name,zs_age); printf("name = %s,age = %d\n",ls_name,ls_age); return 0; }
改进一下: 写一个程序,输出成百上千人的姓名,年龄。
#include <stdio.h> int main(int argc, char **argv) { char *names[] = {"zhangsan", "lisi"}; char ages[] = {10, 16}; char *work[] = {"teacher", "doctor"}; int i; for (i = 0; i < 2; i++) { printf("name = %s, age = %d\n", names[i], ages[i]); } return 0; }
再改进,利用指针,结构体。
#include <stdio.h> struct person { char *name; int age; char *work; void (*printInfo)(struct person *per); }; void printInfo(struct person *per) { printf("name = %s, age = %d, work = %s\n", per->name, per->age, per->work); } int main(int argc, char **argv) { struct person persons[] = { {"zhangsan", 10, "teacher",printInfo}, {"lisi", 16, "doctor",printInfo}, }; persons[0].printInfo(&persons[0]); persons[1].printInfo(&persons[1]); return 0; }
能不能再改进?
#include <stdio.h> struct person { char *name; int age; char *work; void printInfo(void) { printf("name = %s, age = %d, work = %s\n", name, age, work); } }; int main(int argc, char **argv) { struct person persons[] = { {"zhangsan", 10, "teacher"}, {"lisi", 16, "doctor"}, }; persons[0].printInfo(); persons[1].printInfo(); return 0; }
这样就相对优雅一点,再C++中对struct做了两个扩展:
第一,可以直接在结构体中写出函数。
第二,这个函数可以直接访问结构体里面的这些属性。
所以就借此把struct定义为一个新的类别:class。
#include <stdio.h> class person { public: char *name; int age; char *work; void printInfo(void) { printf("name = %s, age = %d, work = %s\n", name, age, work); } }; int main(int argc, char **argv) { struct person persons[] = { {"zhangsan", 10, "teacher"}, {"lisi", 16, "doctor"}, }; persons[0].printInfo(); persons[1].printInfo(); return 0; }
下面会围绕面向对象编程:
1.封装
2.继承
3.多态