简单的C语言结构体实现面向对象的方法

头文件 example.h

#ifndef _EXAMPLE_H_
#define _EXAMPLE_H_

typedef struct {
    void (*FunctionA)(void);
    int (*FunctionB)(int a);
    void (*SetEn)(bool en);
    bool (*GetEn)(void);
}example_t;

#ifndef _EXAMPLE_
extern example_t Example;
#endif // _EXAMPLE_

#endif // _EXAMPLE_H_

源文件 example.c

#include <stdio.h>

#define _EXAMPLE_
#include "example.h"

static bool En = true;

static void sFunctionA(void);
static int sFunctionB(int a);
static void sSetEn(bool en);
static bool sGetEn(void);

example_t Example = {
    .FunctionA=sFunctionA,
    .FunctionB=sFunctionB,
    .SetEn=sSetEn,
    .GetEn=sGetEn
};

static void sFunctionA(void){

}

static int sFunctionB(int a){
    int b = a;
    b++;
    return b;
}

static void sSetEn(bool en){
    En = en;
}

static bool sGetEn(void){
    return En;
}

调用文件 main.c

#include <stdio.h>
#include "example.h"
void main(void){
    int x=0,y=0;
    Example.FunctionA();
    if(Example.GetEn){
        y = Example.FunctionB(x);
        Example.SetEn(false);
    }
}

以下是说明:

#ifndef _EXAMPLE_H_
#define _EXAMPLE_H_

#endif // _EXAMPLE_H_

头文件必不缺少的宏定义,是为了防止重复引用。

typedef struct {
    void (*FunctionA)(void);
    int (*FunctionB)(int a);
    void (*SetEn)(bool en);
    bool (*GetEn)(void);
}example_t;

利用结构体定义函数指针,来实现面向对象的方法。如果希望把方法暴露给其他引用,就再这里需要定义。否则可以不用写入这里。

#ifndef _EXAMPLE_
extern example_t Example;
#endif // _EXAMPLE_

这个外部变量的引用方法,是通过宏定义来实现是否为外部变量。在相应的源文件中利用宏来关闭这个定义。

#define _EXAMPLE_
#include "example.h"

这个就是在源文件里实现关闭外部变量的方法,就是在对应源文件包含头文件前,对宏进行定义。而其他文件引用时不需要宏定义。

static bool En = false;

static void sFunctionA(void);
static int sFunctionB(int a);
static void sSetEn(bool en);
static bool sGetEn(void);

以上是定义变量和声明函数,希望都加上static进行修饰,全局变量需要被其他函数操作,请也封装方法。如果觉得麻烦,就再结构体定义中定义对应变量的指针,利用指针操作。

example_t Example = {
    .FunctionA=sFunctionA,
    .FunctionB=sFunctionB,
    .SetEn=sSetEn,
    .GetEn=sGetEn
};

这个是文件中唯一的一个非static全局变量,也是最主要的面向对象所调用的结构体。在源文件中声明并初始化结构体,就是把对应的函数名付给函数指针。
剩下的就是直接调用了,使用方法可以参考main.c

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值