当我试图编译这段用C++实现函数指针概念的代码时:
#include <iostream>
using namespace std;
class sorting
{
public:
void bubble_sort(int *arr, int size, bool (*compare)(int,int))
{
int i,j,temp = 0;
for(i = 0; i < size - 1; i++)
{
for(j = i+1; j < size; j++)
{
if(compare(arr[i],arr[j]))
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
bool ascending(int x,int y)
{
return x > y;
}
bool descending(int x,int y)
{
return x < y;
}
void display(int *arr,int size)
{
for(int index = 0; index < size; index++)
{
cout<<"arr["<<index<<"]:"<<arr[index]<<endl;
}
}
};
int main()
{
int arr[10] = {99,77,22,33,88,55,44,66,11,100};
sorting s;
cout<<"Ascending order"<<endl;
s.bubble_sort(arr,10,&sorting::ascending);
s.display(arr,10);
cout<<"Descending order"<<endl;
s.bubble_sort(arr,10,&sorting::descending);
s.display(arr,10);
return 0;
}
这些行出现了错误:
s.bubble_sort(arr,10,&sorting::ascending);
s.bubble_sort(arr,10,&sorting::descending);
错误信息如下:
error C2664: 'sorting::bubble_sort' : cannot convert parameter 3 from 'bool (__thiscall sorting::* )(int,int)' to 'bool (__cdecl *)(int,int)'
针对这两行代码,有人能帮我排除这些错误吗?
ascending
和descending
标记为static
。 - Alan Stokes