为什么不能将一个类的常量实例与同一类的非常量实例进行比较?

问题描述

我具有以下功能:

#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)

变量cconst。但是,您的operator==不是 const限定的,因此==的左侧必须是非常量的。

对此的正确解决方法是,如果它是成员函数,则将operator==标记为const

bool operator == (const Coord<T> &p) const {
                                 //  ^^^^^

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...