刷剑指offer的时候发现这么一个问题:
在需要使用谓词的时候,如果谓词是一个类的成员函数,那么我们在定义谓词的时候,必须要定义成静态函数,即,谓词前面需要写static。‘
例如:
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
代码如下:
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
//friend int cmp(const void* a, const void* b);
bool duplicate(int numbers[], int length, int* duplication) {
if(length <= 1)
return false;
qsort(numbers, length, sizeof(int), cmp);
for(int i = 0; i < length; i++){
if(i != length-1 && numbers[i] == numbers[i+1]){
*duplication = numbers[i];
return true;
}
}
return false;
}
static int cmp(const void* a, const void* b){ //这个static非常重要,如果不是static的话程序无法通过;报错:reference to non-static member function must be called
char *p = (char*)a;
char *q = (char*)b;
return *p - *q;
}
};
原因:参考这里 和 这里,简单的说就是qsort函数本来希望我们传递的cmp函数是一个 两个void*参数的函数,咋一看我们也是这么做的,但是由于这是类的成员函数,导致cmp函数在编译时会产生一个implicit parameter,即this指针,所以cmp实际上有三个参数,而qsort希望cmp只有两个参数,这就产生了参数不匹配的问题,也就导致了题目所说的错误,至于为什么错误提示说:必须调用一个非静态函数,这我也不清楚,但是,反正加上static之后,程序就通过了。