【问题标题】:Vector of custom class comparison using == operator使用 == 运算符的自定义类比较向量
【发布时间】:2013-01-12 09:02:38
【问题描述】:

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

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: 来自 'bool std::operator==(const std::vector<_tp _alloc>&, const std::vector <_tp _alloc>&) [with _Tp = cMapEditor::cActionsHistory::cTileState; _Alloc = std::allocator]'

错误:将 'const cMapEditor::cActionsHistory::cTileState' 作为 'bool cMapEditor::cActionsHistory::cTileState::operator==(const cMapEditor::cActionsHistory::cTileState&)' 的 'this' 参数传递会丢弃限定符 [ -fpermissive]

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

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

【问题讨论】:

  • 错误永远不会毫无意义。

标签: c++ list vector comparison containers


【解决方案1】:

您需要将您的成员函数设为const,以便它接受const this 参数:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2020-12-02
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多