2010-07-29 194 views
0

我試圖使用STL,但以下不編譯。 main.cpp中C++:錯誤C2064與STL

#include <set> 
#include <algorithm> 

using namespace std; 

class Odp 
{ 
public: 

    set<int> nums; 

    bool IsOdd(int i) 
    { 
     return i % 2 != 0; 
    } 

    bool fAnyOddNums() 
    { 
     set<int>::iterator iter = find_if(nums.begin(), nums.end(), &Odp::IsOdd); 
     return iter != nums.end(); 
    } 
}; 

int main() 
{ 
    Odp o; 
    o.nums.insert(0); 
    o.nums.insert(1); 
    o.nums.insert(2); 
} 

的錯誤是:

error C2064: term does not evaluate to a function taking 1 arguments 
1>   c:\program files\microsoft visual studio 10.0\vc\include\algorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled 
1>   with 
1>   [ 
1>    _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>, 
1>    _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>, 
1>    _Pr=bool (__thiscall Odp::*)(int) 
1>   ] 
1>   main.cpp(20) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,bool(__thiscall Odp::*)(int)>(_InIt,_InIt,_Pr)' being compiled 
1>   with 
1>   [ 
1>    _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>, 
1>    _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>, 
1>    _Pr=bool (__thiscall Odp::*)(int) 
1>   ] 

我在做什麼錯?

回答

3

它需要被聲明爲靜態:

static bool IsOdd(int i) 

否則,你會問find_if調用實例方法沒有一個實例。

1

IsOdd不以任何方式使用類的內部,所以不要使它成爲一個成員函數。相反,將其作爲獨立功能提取出來。然後您可以撥打find_if&IsOdd

然而,採取東西了一步,其定義爲一個功能對象益處:

#include <functional> 

struct IsOdd : public unary_function<int, bool> 
{ 
    bool operator()(int i) const { return i % 2 != 0; } 
}; 

然後調用find_ifIsOdd()內聯find_if循環內的代碼代替解引用函數指針並進行函數調用。