尝试编译以下代码时出现此编译错误,我该怎么办?
ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.
class MyClass {
int * arr;
// other member variables
MyClass() { arr = new int[someSize]; }
doCompare( const int & i1, const int & i2 ) { // use some member variables }
doSort() { std::sort(arr,arr+someSize, &doCompare); }
};
最佳答案
doCompare
必须是 static
。如果 doCompare
需要来自 MyClass
的数据,您可以通过更改将 MyClass
变成比较仿函数:
doCompare( const int & i1, const int & i2 ) { // use some member variables }
进入
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
并调用:
doSort() { std::sort(arr, arr+someSize, *this); }
另外,doSort
不是缺少返回值吗?
我认为应该可以使用 std::mem_fun
和某种绑定(bind)将成员函数转换为自由函数,但目前我无法理解确切的语法。
编辑: Doh,std::sort
按值获取函数,这可能是个问题。为了解决这个问题,将函数包装在类中:
class MyClass {
struct Less {
Less(const MyClass& c) : myClass(c) {}
bool operator () ( const int & i1, const int & i2 ) {// use 'myClass'}
MyClass& myClass;
};
doSort() { std::sort(arr, arr+someSize, Less(*this)); }
}
关于c++ - 使用成员函数作为比较器的问题排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1902311/