? ? ? 无意中在某个地方看到这样的写法,为此做下笔记,C语言面向对象写法,有点像C++味道。
科普一下函数指针知识
其实函数指针可以类比一般的变量,如下所示:
int a; < = > void haha(void);int * p; < = > void (*heihei)(void);p=&a; < = > heihei = &haha; 左边走义变量a,右边定义函数haha;左边定义int指针,右边定义函数指针;左边赋值指针,右边赋值函数指针;
进入主题:
#include <iostream>typedef struct _SHAPE Shape;struct _SHAPE { float a, b; float (*shapeArea)(Shape);};Shape new_Shape(float a, float b, float(*shapeArea)(Shape));Shape new_Box(float a, float b);Shape new_Tri(float a, float b);Shape new_Shape(float a, float b, float(*shapeArea)(Shape)) { Shape sp; sp.a = a; sp.b = b; sp.shapeArea = shapeArea; return sp;}static float triArea(Shape sp) { return sp.a * sp.b / 2;}static float boxArea(Shape sp) { return sp.a * sp.b;}Shape new_Box(float a, float b) { return new_Shape(a, b, boxArea);}Shape new_Tri(float a, float b) { return new_Shape(a, b, triArea);}int main(){ Shape box1 = new_Box(2.0, 2.0); Shape tri1 = new_Tri(2.0, 2.0); printf("tri:%lfn", tri1.shapeArea(tri1)); printf("box:%lfn", box1.shapeArea(box1)); //std::cout << "Hello World!n";}
运行结果:
39284007