正如你所看到的,隐式解引用的方法看起来就像一个普通的函数调用-这是你所期望的,因为正常的功能名称的函数指针吧!然而,一些老的编译器不支持隐式解引用的方法,但所有的现代编译器应。
为什么要使用函数指针?
有几种情况下,可以使用函数指针。最常见的情况是你写一个函数来执行一个任务(如数组排序),但你希望用户能够定义的任务的一个特定部分将被执行(如数组按升序或降序排序)。让我们仔细看看这个问题,专门用于排序,作为一个例子,可以推广到其他类似的问题。
所有的排序算法工作在一个类似的概念:排序算法走过一堆数字,并对数字比较,并基于这些比较的结果重新排序的数。因此,通过不同的比较(它可以是一个函数),我们可以改变函数类型不影响分类编码其余的路。
这是我们的选择排序例程从以前的教训:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
void
SelectionSort( int
*anArray, int
nSize) { using
namespace
std; for
( int
nStartIndex= 0; nStartIndex < nSize; nStartIndex++) { int
nBestIndex = nStartIndex; //
Search through every element starting at nStartIndex+1 for
( int
nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++) { //
Note that we are using the user-defined comparison here if
(anArray[nCurrentIndex] < anArray[nBestIndex]) //
COMPARISON DONE HERE nBestIndex
= nCurrentIndex; } //
Swap our start element with our best element swap(anArray[nStartIndex],
anArray[nBestIndex]); } } |
1
2
3
4
|
bool
Ascending( int
nX, int
nY) { return
nY > nX; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
void
SelectionSort( int
*anArray, int
nSize) { using
namespace
std; for
( int
nStartIndex= 0; nStartIndex < nSize; nStartIndex++) { int
nBestIndex = nStartIndex; //
Search through every element starting at nStartIndex+1 for
( int
nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++) { //
Note that we are using the user-defined comparison here if
(Ascending(anArray[nCurrentIndex], anArray[nBestIndex])) //
COMPARISON DONE HERE nBestIndex
= nCurrentIndex; } //
Swap our start element with our best element swap(anArray[nStartIndex],
anArray[nBestIndex]); } } |