指向函数的指针,返回void作为另一个函数的参数

时间:2018-03-05 10:25:12

标签: c++ function-pointers

出于学习目的,我想创建一个指向 cstdlib 中定义的函数void qsort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*))的指针,并使用该指针作为同一库中定义的void* bsearch(const void* key, const void* base, size_t num, size_t size, int (*compar)(const void*,const void*));的参数。我试过的代码是这样的:

#include <iostream>
#include <cstdlib>
using namespace std;

class Student
{
public:
    Student(const char *_name, int _id) : name(_name), id(_id) {}
    int operator-(const Student &s) { return (id - s.id); }
private:
    const char *name;
    int id;
};

int compare_by_ID(const void *s1, const void *s2)
{
    return ( *(Student*)s1 - *(Student*)s2 ); 
}

typedef int (*compareFuncPtr)(const void *, const void *);
typedef void (*voidPtr)(void *, size_t, size_t, compareFuncPtr); /*how to use
                                                                 this pointer? 
                                                                 is it defined 
                                                                 correctly for 
                                                                 my purpose?*/
int main()
{
    Student s1("Bob", 8891);
    Student s2("Jack", 8845);
    Student s3("John", 8723);

    Student stdnts[] = {s1, s2, s3};

    compareFuncPtr compare;
    compare = compare_by_studentID;
    qsort(stdnts, 3, size0f(stdnts[0]), compare);    
    //voidPtr qsortPtr;
    //qsortPtr = ??? //to replace qsort(..) bellow:
    bsearch(&s3, qsort(stdnts, 3, sizeof(stdnts[0]), compare)); /*compile error:
                                                                 invalid use of
                                                             void expression.*/
}

如何用函数指针替换bsearch(const void* key, const void* base, size_t num, size_t size,int (*compar)(const void*,const void*))的参数?像这样使用它:bsearch(key, pointerToFunction)

0 个答案:

没有答案