单片机-结构体函数指针使用方法

概述

       C语言结构体对函数指针封装示例(面向对象思想写法)

1、示例:

#include <stdio.h>

int i, j;

struct DATE{
    int year;
    char month;
    char data;
    char hour;
    char min;
    char sec;
};
struct DATE date;

struct str_func {
    int a;
    int b;
    void (*myPrintf)(void);
    void (*init_value)(void);
    void (*date_func)(void);
};

void myPrintf(void) {
    printf("C语言结构体对函数指针封装示例 \r\n");
}

void init_value(void) {
    i = 10;
    j = 20;
}

void date_func(void)
{
    date.year = 2020;
    date.month = 03;
    date.data = 30;
    date.hour = 18;
    date.min = 01;
    date.sec = 25;
}

struct str_func t_func = {
    .a = 5,
    .b = 6,
    .myPrintf = myPrintf,
    .init_value = init_value,
    .date_func = date_func,
};

int main() {
    if (t_func.myPrintf)
    {
        t_func.myPrintf();
    }
    if (t_func.init_value)
    {
        t_func.init_value();
        printf("i=%d,j=%d \r\n", i, j);
    }

    if(t_func.date_func)
    {
        t_func.date_func();
        printf("year:%d, month:%d, data:%d, hour:%d, min:%d, sec:%d \r\n",date.year,date.month,date.data,date.hour,date.min,date.sec);
    }

    return 0;
}

2、运行结果:

发布了71 篇原创文章 · 获赞 79 · 访问量 98万+

猜你喜欢

转载自blog.csdn.net/qq_36075612/article/details/105205154
今日推荐