首页 文章

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

提问于
浏览
2

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

这是我的实现:

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

我用这段代码调用它:

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);
}

但我得到这个错误:

/ 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&)[ with 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 :: Vector3D&)'的'this'参数'丢弃限定符

2 回答

  • 1

    错误

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

    表示你的 operator< 没有做出比较胜利的承诺't modify the left-hand argument, whereas the map requires that the comparison operation shouldn't修改任何东西,并试图将此运算符用于常量实例(映射将键类型存储为const对象) .

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

    bool operator<(const ns3::Vector3D& rhs) const;
    

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

  • 13

    看起来你需要使用const_iterators:

    NeighborSet:迭代

    应该

    NeighborSet ::为const_iterator

    此外,如果您的编译器支持它(C 0x),请使用cbegin和cend而不是begin和end .

相关问题