【问题标题】:error: passing ‘const …'’ as ‘this’ argument of ‘…’ discards qualifiers错误:将“const ...”作为“...”的“this”参数传递会丢弃限定符
【发布时间】:2014-01-04 11:49:27
【问题描述】:

我和hereherehere 有同样的问题,除了我为参数和函数设置了 const:

#include <unordered_map>
#include <functional>

namespace zzz {

struct identity_t {
    static const int ID_SIZE = 5;
    static const int LSB = 4; // = ID_SIZE - 1
    unsigned char id[ID_SIZE];
    inline bool operator< (const identity_t& rhs) const {
        for (int i = 0; i < ID_SIZE; i++) if (id[i] != rhs.id[i]) return (id[i] < rhs.id[i]);
        return false; // equal
    }
    unsigned char operator[] (const int& i) {return id[i];}
};

class hash_identity_t {
public:
    long operator()(const identity_t& x) const {
        return (long) x[identity_t::LSB];
    }
};

class equal_to_identity_t {
public:
     bool operator()(const identity_t& lhs, const identity_t& rhs) const {
         for (int i = 0; i < identity_t::ID_SIZE; i++) if (lhs[i] != rhs[i]) return false;
          return true;
     }
};

但我有同样的编译错误:

error: passing 'const zzz::identity_t' as 'this' argument of 'unsigned char zzz::identity_t::operator[](const int&)' discards qualifiers [-fpermissive]

【问题讨论】:

  • 你没有为函数添加 const...
  • 好吧,您将const 放在其中一个功能上,但错误告诉您您也需要在operator[] 上使用它。这向我表明,您并不真正知道为什么要将 const 放在函数上。你呢?
  • 看了你的评论,很明显。但首先,解释错误消息并非如此。在我的理解中,参数的 const 意味着函数不会修改它,但方法的 const 对我来说不是很清楚。

标签: c++ constants unordered-map


【解决方案1】:

您正试图在const 函数long hash_identity_t::operator( const identity_t&amp; x ) 中的const 参数上调用非const 函数(identity_t::operator[])。

使identity_t::operator[] 不变。

//--------------------------------------vvvvv
unsigned char operator[] (const int& i) const {return id[i];}

【讨论】:

    【解决方案2】:

    使用 std::map 的at() 方法。

    const mapped_type & at (const key_type &__k) const 
    

    【讨论】:

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