使用函数指针

来源:互联网 发布:国中土耳其 知乎 编辑:程序博客网 时间:2024/06/05 22:32

为什么要使用函数指针

有几种情况下,函数指针可以使用。最常见的情况是你写一个函数来执行一个任务(如数组排序),但你希望用户能够定义该任务的特定部分将被执行(如数组按升序或降序排序)。让我们仔细看看这个问题,专门用于分类例如可以推广到其他类似的问题

所有的排序算法工作在一个类似的概念:排序算法走过一堆数字,并对数字进行比较,并基于这些比较结果的数字重新排序。因此通过不同的比较(它可以是一个函数)我们可以改变函数类型不影响其他代码的方式排序

这是我们的选择排序程序从以前的教训

2345678910111213141516171819void 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]);    }

正如你可以看到,使用函数指针在这方面提供了一个很好的办法让来电者“钩”,它的功能有你以前写的测试,这有助于促进代码重用!以前,如果你想在一个数组排序降序和升序,你需要的排序例程的多个版本。现在你可以有一个版本,可以任何方式对方的欲望

漂亮的定义函数指针

让我们面对它-函数指针的语法是丑陋的。然而typedef可以使函数指针看起来更像普通变量


0 0