结构体中的函数指针

来源:百度文库 编辑:神马文学网 时间:2024/04/28 20:50:30
2007-09-04 17:29
C语言真是很灵活,今天发现结构中函数指针的应用,就查了些资料总结一下。
其实在结构体已经和C++中的类功能差不多,只是其是面向过程,没有了作用域的要求,如public等
你可以在结构体中定义函数函数指针,然后对其调用和类调用方法一样,在调用时对其赋值(你要调用的指针),这样看来,C也可以临时客串一下面向对象了。呵呵.大家可以试一下.
1 #include
2 struct square
3 {
4         int length;
5         int width;
6         int height;
7         int (*add)(int a,int b);
8 };
9 int square_add(int a,int b)
10 {
11         return a + b;
12 }
13 int bulk(int length,int width,int height)
14 {
15         struct square squ =
16         {
17                 .length = length,
18                 .width = width,
19                 .height = height,
20                 add:square_add,
21         };
22
23         printf("Add() is %d\n",squ.add(100,200));
24         printf("Length is %d\n",squ.length);
25         printf("Width is %d\n",squ.width);
26         printf("Height is %d\n",squ.height);
27         return squ.length * squ.width * squ.height;
28 }
29 int main()
30 {
31         printf("The square is %d\n",bulk(100,200,300));
32         return 0;
33 }