【问题标题】:'const' qualifiers cannot be applied to 'std::vector<long unsigned int>&''const' 限定符不能应用于 'std::vector<long unsigned int>&'
【发布时间】:2019-01-25 04:50:26
【问题描述】:

我在 linux 上有一个 c++11 项目,其中我使用了以下签名,它无法在 linux 上编译但在 windows 上编译

错误:

error: 'const' qualifiers cannot be applied to 'std::vector<long unsigned int>&'

error: 'const' qualifiers cannot be applied to 'std::map<long unsigned int, long unsigned int>&'

函数是

    bool debugGlobalDs(std::vector<size_t> & const elementIds ,
 std::map<long unsigned int, long unsigned int>& const mapElementIdToGlobalIndex)
    {
    ....
    return true
    }

为什么我不能在这里使用 const 限定符?一旦我删除它,它也可以在 Linux 上正常编译。

【问题讨论】:

  • 你不能有 const 引用。

标签: c++11 constants


【解决方案1】:

const 放错地方了。应该是const std::vector&lt;size_t&gt;&amp; elementIds
这意味着该函数不允许更改elementIds

map 也是如此。
应该是const std::map&lt;long unsigned int, long unsigned int&gt;&amp; mapElementIdToGlobalIndex

const 在 OP 中的位置将引用标记为 const。由于无论如何都无法更改引用,因此无需这样做。

【讨论】:

  • 从右到左读取。我想将 elementIds 设为 const 以便它们无法更改。将 const 放在首位意味着 elementIds 是对 const 向量的引用。
  • 即使这样,您也无法更改elementIds。查看演示:godbolt.org/z/b4pY_a.
  • @MAG:正确。但是没有办法引用const,因为没有操作会改变引用的开头,所以没有禁用。
  • @BenVoigt 感谢您的评论。它更清楚了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 2012-03-07
相关资源
最近更新 更多