2010-07-29 164 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循环内的代码代替解引用函数指针并进行函数调用。