兴趣是最好的学习契机!
全部博文(127)
分类: C/C++
2014-06-19 13:40:46
然而,你又是否知道,Windows2000是用7500W行C语言编写出来的.如果单单是面向过程,估计这样编写出来的OS会混乱不堪.
其实,你知道C语言很强大,但是你可能不知道它强大到能够实现面向对象编程的.现在就由我来介绍一下具体的实现方法吧...
C语言没有class这样的关键字,只有struct.但是struct只能保存数据成员,不能保存方法.可是,C语言的精髓就在于指针,在struct中加入相应方法的函数指针就可以完全实现了类的功能了.只要在创建实例,初始化时把相应的函数指针赋值就行了.
有了类还不能实现面向对象.我们还需要继承呀.那么怎样继承呢?也很简单,直接把父类作为子类的第一个数据元素就搞掂了.
继承搞掂了,还是不行的.我们还需要封装好每一个类.实现封装的方法就是使用static和extern这两个关键字就行了.详细的理由,自己看回一下C语言的课本有关生命周期的介绍那部分就可以知道了.
就这样,我们就用C语言实现了面向对象的编程了.
- struct shape;
- struct shape_ops
- {
- float (*so_area)(struct shape*);
- int (*so_perimeter)(struct shape*);
- };
- struct shape
- {
- int* s_type;
- char* s_name;
- struct shape_ops* s_ops;
- };
- float shape_area(struct shape* s)
- {
- return s->s_ops->so_area(s);
- }
- int shape_perimeter(struct shape* s)
- {
- return s->s_ops->so_perimeter(s);
- }
- struct triangle
- {
- struct shape t_base;
- int t_side_a;
- int t_side_b;
- int t_side_c;
- };
- float triangle_area(struct shape* s)
- {
- struct triangle* t=(struct triangle*)s;
- int a=t->t_side_a;
- int b=t->t_side_b;
- int c=t->t_side_c;
- float p=(a+b+c)/2;
- return sqrt(p*(p-a)*(p-b)*(p-c));
- }
- int triangle_perimeter(struct shape* s)
- {
- struct triangle* t=(struct triangle*)s;
- int a=t->t_side_a;
- int b=t->t_side_b;
- int c=t->t_side_c;
- return a+b+c;
- }
- struct shape_ops triangle_ops=
- {
- triangle_area,
- triangle_perimeter,
- };
- struct triangle* triangle_create(int a,int b,int c)
- {
- struct triangle* ret=(struct triangle*)malloc(sizeof (*ret));
- ret->t_base.s_name="triangle";
- ret->t_base.s_ops=&triangle_ops;
- ret->t_side_a=a;
- ret->t_side_b=b;
- ret->t_side_c=c;
- return ret;
- }
- struct rectangle
- {
- struct shape r_base;
- int r_width;
- int r_height;
- };
- float rectangle_area(struct shape* s)
- {
- struct rectangle* r=(struct rectangle*)s;
- return r->r_width*r->r_height;
- }
- int rectangle_perimeter(struct shape* s)
- {
- struct rectangle* r=(struct rectangle*)s;
- return (r->r_width+r->r_height)*2;
- }
- struct shape_ops rectangle_ops=
- {
- rectangle_area,
- rectangle_perimeter,
- };
- struct rectangle* rectangle_create(int width, int height)
- {
- struct rectangle* ret=(struct rectangle*)malloc(sizeof(*ret));
- ret->r_base.s_name="rectangle";
- ret->r_base.s_ops=&rectangle_ops;
- ret->r_height=height;
- ret->r_width=width;
- return ret;
- }
- int main()
- {
- struct shape* s[4];
- s[0]=triangle_create(5,5,4);
- s[1]=triangle_create(3,4,5);
- s[2]=rectangle_create(10,12);
- s[3]=rectangle_create(5,8);
- int i=0;
- for(i=0;i<4;i++)
- {
- float area=shape_area(s[i]);
- int perimeter=shape_perimeter(s[i]);
- char* name=s[i]->s_name;
- printf("name:%s ,area:%.2f ,perimeter:%d\n",name,area,perimeter);
- }
- return 0;
- }
- name:triangle ,area:9.17 ,perimeter:14
- name:triangle ,area:6.00 ,perimeter:12
- name:rectangle ,area:120.00 ,perimeter:44
- name:rectangle ,area:40.00 ,perimeter:26