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

标签 c++ class compiler-errors constants operator-overloading

我有以下功能:

#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)
变量cconst。但是,您的operator==不是const限定符,因此==的左侧必须为非const。
正确的解决方法是,如果它是成员函数,则将operator==标记为const:
bool operator == (const Coord<T> &p) const {
                                 //  ^^^^^

关于c++ - 为什么不能将一个类的常量实例与同一类的非常量实例进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63344332/

相关文章:

php - PHP include 或 require 类与原始编写的类有什么区别?

compiler-errors - fprintf 未在此范围内声明

c++ - QtSQL双插入数据库

java - 类对象的生命周期 : Java

c++ - 什么工具可以将DLL反编译成C++源代码?

C#泛型,传递类

linux - 无法在 Linux Mint 15 中编译简单的 c 程序

c# Dapper - 在 QueryAsync 方法上使用 linq

c++ - 为什么我们通过了链接阶段仍然错过了符号?

c++ - 使用 C++ 执行 SOAP 或 REST 的选项