c++ - 使用 == 运算符的自定义类比较 vector

标签 c++ list vector comparison containers

一个伪代码(这是我的类):

struct cTileState   {
        cTileState(unsigned int tileX, unsigned int tileY, unsigned int texNr) : tileX(tileX), tileY(tileY), texNr(texNr) {}
        unsigned int tileX;
        unsigned int tileY;
        unsigned int texNr;

        bool operator==(const cTileState & r)
        {
            if (tileX == r.tileX && tileY == r.tileY && texNr == r.texNr) return true;
            else return false;
        }
    };

然后我有两个容器:

       std::list < std::vector <cTileState> > changesList;  //stores states in specific order
       std::vector <cTileState> nextState;

在程序的某个地方,我想在我的状态交换函数中这样做:

      if (nextState == changesList.back()) return;

但是,当我想编译它时,我遇到了一些对我来说毫无意义的错误,例如:

/usr/include/c++/4.7/bits/stl_vector.h:1372:58: required from ‘bool std::operator==(const std::vector<_Tp, _Alloc>&, const std::vector<_Tp, _Alloc>&) [with _Tp = cMapEditor::cActionsHistory::cTileState; _Alloc = std::allocator]’

error: passing ‘const cMapEditor::cActionsHistory::cTileState’ as ‘this’ argument of ‘bool cMapEditor::cActionsHistory::cTileState::operator==(const cMapEditor::cActionsHistory::cTileState&)’ discards qualifiers [-fpermissive]

它说 STL_vector.h 中有问题,我不尊重 const 限定符,但老实说,没有我不尊重的 const 限定符。这里有什么问题吗?

此外,ide 不会向我显示文件中任何特定行中的错误 - 它只会显示在构建日志中,仅此而已。

最佳答案

您需要使您的成员函数const,以便它接受一个const this 参数:

bool operator==(const cTileState & r) const
                                      ^^^^^

更好的是,让它成为一个免费的功能:

bool operator==(const cTileState &lhs, const cTileState & rhs)

使成员函数 const 大致对应于 const cTileState &lhs 中的 const,而非 const 成员函数将具有 cTileState &lhs 等效。错误指向的函数尝试使用 const 第一个参数调用它,但您的函数只接受非常量参数。

关于c++ - 使用 == 运算符的自定义类比较 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14291849/

相关文章:

python - 在 bool 列表中获取 True 值的索引

scala - 在scala中使用map和reduce进行矢量积

c++ - 为什么以下 C++ 代码无法编译?

c++ - (简单例子)MPI parallel io writing garbage

algorithm - 什么是对偶排序

c++ - 具有 vector 的类是否有成员有内存问题

c++ - SIGSEGV 通过写入局部变量

c++ - 无法识别 GMock 宏? YCM 给我错误,但 Bazel 构建良好

c++ - 我是否需要使用内存屏障来保护共享资源?

c++ - 如何获取存储在 C++ 列表中的类对象?