C语言函数指针实现多态特性

1、函数指针

函数指针是指向函数的指针变量,本质上是一个指针,类似于int*,只不过它是指向一个函数的入口地址。有了指向函数的指针变量后,就可以用该指针变量调用函数,就如同用指针变量引用其他类型变量一样。

指针函数一般有两个作用:调用函数和做函数的参数

2、函数指针实现多态

先来上一段代码:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef int(*PipeProcessor)(void* args, int val);   // Function pointer
typedef struct Pipe
{
struct Pipe* next;
PipeProcessor handler;
void* args;
} Pipe;

void init(Pipe* pipe)
{
pipe->next = NULL;
pipe->handler = NULL;
pipe->args = NULL;
}

void process(Pipe* first, int val)
{
Pipe* it = first;
while (it != NULL)
{
val = (*(it->handler))(it->args, val);
it = it->next;
}
}

void attach(Pipe* front, Pipe* next)
{
front->next = next;
}

int printPipe(void* args, int val)
{
printf("val = %d\n", val);
return val;
}

int addPipe(void* args, int val)
{
return (*(int*)(args)) + val;
}

int multiPipe(void* args, int val)
{
return (*(int*)(args)) * val;
}

int main()
{
Pipe first;
int first_args = 1;
Pipe second;
int second_args = 2;
Pipe third;
int third_args = 10;
Pipe last;

init(&first);
first.handler = addPipe;        // Use the Function pointer to realize polymorphic
first.args = &first_args;

init(&second);
second.handler = multiPipe;
second.args = &second_args;
attach(&first, &second);

init(&third);
third.handler = addPipe;
third.args = &third_args;
attach(&second, &third);

init(&last);
last.handler = printPipe;
attach(&third, &last);

process(&first, 1);
process(&first, 2);
process(&first, 3);

system("pause");
return 0;
}

以上为通过函数指针来实现的多态特性,通过Pipe的handler变量(实质上是一个指针变量)指向不同的函数,来实现多态。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值