2011-11-30 60 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); 
} 
相关问题