c++ - operator< std::set 的重载

标签 c++ stl

这是我的代码:

#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/

相关文章:

c++ - 为什么我们再次从结构对象创建结构变量?

c++ - SDL 切换全屏显示框架

c++ - STL 文档

c++ - 使用C++标准库以对数时间进行堆化

c++ - 函数中的表达式语法错误帮助! C/C++

c++ - 观察中心时围绕球体旋转相机(使用四元数)

C++ 一个文件多个类

c++ - std::queue<T, list<T>>::size() 在 O(n) 中很慢?

c++ - 如何使用 (lambda) 函数填充 C++ 容器?

c++ - 为什么 `std::all_of` 不使用 `std::invoke` ?