【问题标题】:Error using custom operator< with std::less将自定义运算符 < 与 std::less 一起使用时出错
【发布时间】:2011-04-12 15:35:46
【问题描述】:

我正在尝试重载 &lt; 运算符,但遇到了问题。

这是我的实现:

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 >, _Compare = std::less<:vector3d> , _Alloc = std::allocator<:pair ns3::vector3d std::vector ns3::olsr::neighbortuple std::allocator> > >]'
../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

【问题讨论】:

  • 能否请您以更连贯的方式重新发布您的代码:) 现在几乎不可能辨别出不同的消息和代码位。
  • 我已代表 OP 对其进行了编辑以提高可读性。
  • 原来有几个人同时编辑了这个。我只修改了语法,没有修改代码。我真的无法决定应该保留哪些更改,因此之前编辑过它的任何人都可以随意回滚 =)

标签: c++


【解决方案1】:

看起来你需要使用 const_iterators:

NeighborSet::迭代器

应该是

NeighborSet::const_iterator

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

【讨论】:

    【解决方案2】:

    错误

    将“const ns3::Vector3D”作为 ‘int’的‘this’参数 ns3::Vector3D::operator

    表示您的 operator&lt; 没有承诺比较不会修改左侧参数,而映射要求比较操作不应该修改任何内容,并尝试将此运算符用于常量实例(映射将键类型存储为 const 对象)。

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

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

    顺便说一句,你为什么不返回一个布尔值(结果必须是真假)?

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      相关资源
      最近更新 更多