問題描述
嘗試編譯以下代碼時出現此編譯錯誤,我該怎么辦?
trying to compile the following code I get this compile error, what can I do?
ISO C++ 禁止取地址不合格的或括號內的非靜態成員函數形成一個指向成員函數的指針.
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
must be static
. If doCompare
needs data from MyClass
you could turn MyClass
into a comparison functor by changing:
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
是不是缺少返回值?
Also, isn't doSort
missing a return value?
我認為應該可以使用 std::mem_fun
和某種綁定將成員函數轉換為自由函數,但目前我無法理解確切的語法.
I think it should be possible to use std::mem_fun
and some sort of binding to turn the member function into a free function, but the exact syntax evades me at the moment.
Doh,std::sort
按值獲取函數,這可能是一個問題.為了解決這個問題,將函數包裝在類中:
Doh, std::sort
takes the function by value which may be a problem. To get around this wrap the function inside the class:
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)); }
}
這篇關于使用成員函數作為比較器進行排序的問題的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!