【问题标题】:C++ struct - Passing const as this argument discards qualifiersC++ struct - 将 const 作为此参数传递会丢弃限定符
【发布时间】:2013-05-08 01:57:17
【问题描述】:

所以,我正在尝试创建一个结构 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&lt;(const TileSet&amp;)' discards qualifiers [-fpermissive]这是什么意思?将变量更改为 const 不起作用,无论如何我都需要它们是非常量的。

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

std::priority_queue&lt;be::Object::TileSet&gt; tileset_queue;

【问题讨论】:

标签: c++ reference constants


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    尝试使 operator

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      相关资源
      最近更新 更多