简单的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 

#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 
#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

你可能感兴趣的:(C语言)