問(wèn)題描述
嘗試編譯以下代碼時(shí)出現(xiàn)此編譯錯(cuò)誤,我該怎么辦?
trying to compile the following code I get this compile error, what can I do?
ISO C++ 禁止取地址不合格的或括號(hào)內(nèi)的非靜態(tài)成員函數(shù)形成一個(gè)指向成員函數(shù)的指針.
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
需要來(lái)自 MyClass
的數(shù)據(jù),您可以通過(guò)更改將 MyClass
變成一個(gè)比較函子:
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 }
進(jìn)入
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
并調(diào)用:
doSort() { std::sort(arr, arr+someSize, *this); }
另外,doSort
是不是缺少返回值?
Also, isn't doSort
missing a return value?
我認(rèn)為應(yīng)該可以使用 std::mem_fun
和某種綁定將成員函數(shù)轉(zhuǎn)換為自由函數(shù),但目前我無(wú)法理解確切的語(yǔ)法.
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
按值獲取函數(shù),這可能是一個(gè)問(wèn)題.為了解決這個(gè)問(wèn)題,將函數(shù)包裝在類中:
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)); }
}
這篇關(guān)于使用成員函數(shù)作為比較器進(jìn)行排序的問(wèn)題的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!