这是我的代码:
#include <iostream>
#include <set>
#include <string>
class widget
{
public:
widget(unsigned id) :
m_id(id)
{
};
~widget(){};
unsigned id(){ return m_id; };
bool active(){ return m_active; };
void set_active(bool active){ m_active = active; };
friend bool operator<(const widget& lhs, const widget& rhs);
bool operator<(const widget& rhs)
{
return m_id < rhs.m_id;
}
private:
unsigned m_id;
bool m_active{false};
};
bool operator<(const widget& lhs, const widget& rhs)
{
return lhs.m_id < rhs.m_id;
}
int main()
{
std::set<widget> widgets;
widget foo(5);
widget bar(2);
widgets.insert(foo);
widgets.insert(bar);
for(const auto& hi : widgets)
std::cout << hi.id() << std::endl;
}
编译时出现错误:
将“const widget”作为“unsigned int widget::id()”的“this”参数传递会丢弃限定符 [-fpermissive]
而且我不明白发生了什么。我做错了运算符重载吗?另外,我是否需要将 operator< 作为具有一个参数的成员函数和具有两个参数的自由函数?
最佳答案
为你的函数 id
添加一个 const
限定符:
unsigned id() const { return m_id; }
原因是在您的循环中,您使用 const
引用遍历您的 widgets
集 - 禁止对此调用非常量成员函数。
关于c++ - operator< std::set 的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37677513/