问题描述
我具有以下功能:
#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)
上给我一个错误:
错误:将“ const Coord
”作为“ this”参数传递会舍弃限定词[-fpermissive]
解决方法
在您的比较中:
if (c == i)
变量c
是const
。但是,您的operator==
不是 const限定的,因此==
的左侧必须是非常量的。
对此的正确解决方法是,如果它是成员函数,则将operator==
标记为const
:
bool operator == (const Coord<T> &p) const {
// ^^^^^