c++ - 将自定义运算符 < 与 std::less 一起使用时出错

标签 c++

我正在尝试使 < 过载运算符(operator),但遇到了问题。

这是我的实现:

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: In member function ‘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: instantiated from ‘_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: instantiated from here
/usr/include/c++/4.1.2/bits/stl_function.h:227: error: passing ‘const ns3::Vector3D’ as ‘this’ argument of ‘int ns3::Vector3D::operator<(const ns3::Vector3D&)’ discards qualifiers

最佳答案

错误

passing ‘const ns3::Vector3D’ as ‘this’ argument of ‘int ns3::Vector3D::operator<(const ns3::Vector3D&)’ discards qualifiers

表示你的operator<不 promise 比较不会修改左侧参数,而 map 要求比较操作不应该修改任何东西,并试图将此运算符用于常量实例( map 存储键类型作为 const 对象)。

简而言之,此类运算符重载不得改变任何内容,并且两个操作数都必须声明为 const。由于您已将 this 作为成员函数重载,因此您必须使函数本身成为常量。

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

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

关于c++ - 将自定义运算符 < 与 std::less 一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3717282/

相关文章:

c++ - 使用 C++ 获取 linux 机器的屏幕截图

c++ - 使用 C 或 C++ 检查互联网连接的最快方法是什么?

c++ - 动态数组推送功能 - 它是如何工作的?

c++ - 无法在 Visual C++ 2010 中运行我的第一个 Win32 应用程序

c++ - 为什么即使在 'ss.fail()' 为真(这里 'ss' 是一个 stringstream 对象)之后循环也不终止?

c++ - 多线程 - 类中的异步线程

c++ - 关于堆清理的 C++ 约定理论,一个建议的构建,是好的做法吗?

c++ - 什么工具可以将DLL反编译成C++源代码?

c++ - 将对象传递给方法 C++

c++ - 将 Objective-C 协议(protocol)转换为 C++ 中的等效协议(protocol)