C++结构体 - 将const作为this参数传递会丢弃限定符

3

所以,我正试图创建一个结构体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' 作为 'bool TileSet::operator<(const TileSet&)' 的 'this' 参数会丢弃限定符[-fpermissive]。这是什么意思?将变量更改为const并没有起作用,而且我需要它们是非const的。当我尝试执行以下操作时发生错误:std :: priority_queue <be :: Object :: TileSet> tileset_queue;

可能是C++“传递this会丢弃限定符”的重复问题。 - Jack
我猜在提问之前你可以先搜索一下谷歌: http://stackoverflow.com/questions/10226787/c-passing-as-this-discards-qualifiers https://dev59.com/dG025IYBdhLWcg3wfmHw https://dev59.com/xEzSa4cB1Zd3GeqPm3Zi - Jack
2个回答

6
你需要在operator<方法的定义中添加const限定符:
bool operator<(const TileSet &b) const
                               // ^^^ add me
{
    return this->gid < b.gid;
}

这告诉编译器函数中传递的this参数是常量,否则它将不允许您将一个常量引用作为this参数传递。


0
尝试将 operator < 设为常量成员函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接