使用自定义运算符<with std :: less时出错

bah*_*har 2 c++

我试图重载<运算符,但遇到问题.

这是我的实现:

int Vector3D::operator < (const Vector3D &vector)
{
   if(x<vector.x)
       return 1;
   else
       return 0;
}
Run Code Online (Sandbox Code Playgroud)

我用这段代码调用它:

std::map<Vector3D, std::vector<const NeighborTuple *> > position; 
std::set<Vector3D> pos; 
for (NeighborSet::iterator it = N.begin(); it != N.end(); it++)
{
    NeighborTuple const  &nb_tuple = *it;

    Vector exposition;
    pos.insert (exposition);
    position[exposition].push_back (&nb_tuple);
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

/usr/include/c++/4.1.2/bits/stl_function.h:在成员函数'bool std :: less <_Tp> :: operator()(const _Tp&,const _Tp&)const [with _Tp = ns3 :: Vector3D ]':
/usr/include/c++/4.1.2/bits/stl_map.h:347:从'_Tp&std :: map <_Key,_Tp,_Compare,_Alloc> :: operator [](const _Key&)[与...实例化_Key = ns3 :: Vector3D,_Tp = std :: vector <const ns3 :: olsr :: NeighborTuple*,std :: allocator <const ns3 :: olsr :: NeighborTuple*>>,_ Compare = std :: less <ns3: :Vector3D>,_ Alloc = std :: allocator <std :: pair <const ns3 :: Vector3D,std :: vector <const ns3 :: olsr :: NeighborTuple*,std :: allocator <const ns3 :: olsr :: NeighborTuple*
>>>> ]] ../src/routing/olsr/olsr-routing-protocol.cc:853:从这里实例化
/usr/include/c++/4.1.2/bits/stl_function.h:227:错误:将'const ns3 :: Vector3D'作为'int ns3 :: Vector3D :: operator <(const ns3 ::)的'this'参数传递Vector3D&)'丢弃限定符

Unc*_*ens 13

错误

将'const ns3 :: Vector3D'作为'int ns3 :: Vector3D :: operator <(const ns3 :: Vector3D&)'的'this'参数传递'丢弃限定符

表示你operator<没有做出比较不会修改左手参数的承诺,而地图要求比较操作不应修改任何东西,并试图将此运算符用于常量实例(地图存储key-types as const objects).

简而言之,这样的运算符重载不能改变任何东西,并且两个操作数必须声明为const.由于您已将此作为成员函数重载,因此必须使函数本身为const.

bool operator<(const ns3::Vector3D& rhs) const;
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你为什么不归还一个博尔(结果必须是真还是假)?