一个伪代码(这是我的类):
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/