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變量(實質上是一個指針變量)指向不同的函數,來實現多態。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章