我有以下功能:
#include <cstdint>
using int_32 = int32_t;
bool func(const Coord<int_32> c)
{
for (Coord<int_32> i : boxes)
if (c == i)
return 0;
return 1;
}
Coord<int_32>
是具有两个类型为 int ( int32_t )的成员的结构。这是其重载的 == 运算符:
bool operator == (const Coord<T> &p)
{
if (this -> x == p.x &&
this -> y == p.y)
return 1;
return 0;
}
它给我if (c == i)
一个错误:error: passing 'const Coord<int>' as 'this' argument discards qualifiers [-fpermissive]
最佳答案
在您的比较中:
if (c == i)
变量c
是const
。但是,您的operator==
不是const限定符,因此==
的左侧必须为非const。正确的解决方法是,如果它是成员函数,则将
operator==
标记为const
:bool operator == (const Coord<T> &p) const {
// ^^^^^
关于c++ - 为什么不能将一个类的常量实例与同一类的非常量实例进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63344332/