概述

      无意中在某个地方看到这样的写法,为此做下笔记,C语言面向对象写法,有点像C++味道。

科普一下函数指针知识

其实函数指针可以类比一般的变量,如下所示:

int   a; < = > void haha(void);
int * p; < = > void (*heihei)(void);
p=&a;    < = > heihei = &haha;
  1. 左边走义变量a,右边定义函数haha;
  2. 左边定义int指针,右边定义函数指针;
  3. 左边赋值指针,右边赋值函数指针;

进入主题:

#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:%lf\n", tri1.shapeArea(tri1));
    printf("box:%lf\n", box1.shapeArea(box1));

    //std::cout << "Hello World!\n";
}

运行结果:

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐