【发布时间】:2015-12-25 15:08:36
【问题描述】:
当我试图编译这段代码以使用 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)'
对于这两行。 有人可以帮我消除这些错误吗?
【问题讨论】:
-
最简单的解决方案?制作比较函数
static。然后跟我重复一遍:指向函数的指针与指向成员函数的指针不同。 -
最简单的解决方法是将
ascending和descending标记为static。
标签: c++ function class pointers