C ++ struct - 传递const作为此参数会丢弃限定符

时间:2013-05-08 01:57:18

标签: c++ reference const

所以,我正在尝试创建一个结构TileSet并覆盖<运算符,然后将TileSet放在优先级队列中。我已经读过我不能在const引用上调用非const方法,但实际上不应该有问题,我只是访问成员,而不是更改它们:

    struct TileSet
    {

        // ... other struct stuff, the only stuff that matters

        TileSet(const TileSet& copy)
        {
            this->gid = copy.gid;
            this->spacing = copy.spacing;
            this->width = copy.width;
            this->height = copy.height;
            this->texture = copy.texture;
        }

        bool operator<(const TileSet &b)
        {
            return this->gid < b.gid;
        }
    }; 

错误消息告诉我:传递'const TileSet' as 'this' argument of 'bool TileSet::operator<(const TileSet&)' discards qualifiers [-fpermissive]这是什么意思?将变量更改为const不起作用,无论如何我都需要它们是非常量的。

我尝试这样做时会发生错误:

std::priority_queue<be::Object::TileSet> tileset_queue;

2 个答案:

答案 0 :(得分:5)

您需要在const方法的定义中添加operator<限定符:

bool operator<(const TileSet &b) const
                               // ^^^ add me
{
    return this->gid < b.gid;
}

这告诉编译器传递给函数的this参数是const,否则它不允许你将const引用作为this参数传递。

答案 1 :(得分:0)

尝试制作运营商&lt;一个const成员函数。