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变量(实质上是一个指针变量)指向不同的函数,来实现多态。