2011-11-30 61 views
4

我想使用我自己的結構'Point2'作爲鍵的映射,但是我收到錯誤,我不知道是什麼原因造成的,因爲我爲Point2結構聲明一個'運營商<'。std :: less <>不能使用我的std :: map

代碼:

std::map<Point2, Prop*> m_Props_m; 
std::map<Point2, Point2> m_Orders; 

struct Point2 
{ 
    unsigned int Point2::x; 
    unsigned int Point2::y; 

Point2& Point2::operator= (const Point2& b) 
    { 
     if (this != &b) { 
      x = b.x; 
      y = b.y; 
     } 
     return *this; 
    } 

    bool Point2::operator== (const Point2& b) 
    { 
     return (x == b.x && y == b.y); 
    } 

    bool Point2::operator< (const Point2& b) 
    { 
     return (x+y < b.x+b.y); 
    } 

    bool Point2::operator> (const Point2& b) 
    { 
     return (x+y > b.x+b.y); 
    } 
}; 

錯誤:

1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Point2' (or there is no acceptable conversion) 
1>c:\testing\project\point2.h(34): could be 'bool Point2::operator <(const Point2 &)' 
1>while trying to match the argument list '(const Point2, const Point2)' 
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(124) : while compiling class template member function 'bool std::less<_Ty>::operator()(const _Ty &,const _Ty &) const' 
1>   with 
1>   [ 
1>    _Ty=Point2 
1>   ] 

有人能看到什麼導致這個問題?

回答

9

std::map預計operator <一個const版本:

// note the final const on this line: 
bool Point2::operator< (const Point2& b) const 
{ 
    return (x+y < b.x+b.y); 
} 

它沒有意義的有operator==operator>非const版本,這些應該是const爲好。

正如ildjarn指出的那樣,這是一個明確的例子,您可以將這些運算符實現爲自由函數而不是成員函數。一般而言,您應該將這些運營商視爲免費功能,除非他們需要作爲成員功能。這裏有一個例子:

bool operator<(const Point2& lhs, const Point2& rhs) 
{ 
    return (lhs.x + lhs.y) < (rhs.x + rhs.y); 
} 
+0

就解決它..謝謝! – xcrypt

+0

更好的是,他們不應該被定義爲集體成員,而是作爲免費功能... – ildjarn

+0

同意。在這個特定的例子中,免費函數更適合,但我只是發佈了幫助OP的答案。 – Chad

3

operator<應定義爲const,其實這樣如果你的其他比較操作,而在一般情況下,不會發生變異的類中的任何方法:

bool Point2::operator== (const Point2& b) const 
{ 
    return (x == b.x && y == b.y); 
} 

bool Point2::operator< (const Point2& b) const 
{ 
    return (x+y < b.x+b.y); 
} 

bool Point2::operator> (const Point2& b) const 
{ 
    return (x+y > b.x+b.y); 
} 
相關問題