结构向量 - 没有看到我对运算符==的定义

Vector of structs - not seeing my definition for operator==

本文关键字:运算符 定义 向量 结构      更新时间:2023-10-16

我有一个名为Something的类,它有两个东西:一个字符串和一个指令向量。在该类中,我想定义运算符==。但是,当我尝试编译时出现错误:

error: no match for ‘operator==’ in ‘* __first1 == * __first2’

这发生在我使用 == 比较 Something 中的两个向量的行(因为向量有方便的定义,我想使用它)。

说明如下:

struct instruction
{
    int instr;
    int line;
    bool operator==(const instruction& rhs)
    {
        return (instr == rhs.instr) && (line == rhs.line);
    }
};

我一直在寻找解决方案无济于事。似乎来自 STL 的向量在比较这些元素时没有看到我为我的结构定义的运算符==。

您尚未显示实际失败的代码,但很可能是如下所示的情况:

int main()
{
  vector <instruction> ins;
  vector <instruction>::const_iterator itA = /*...*/, itB = /*...*/;
  bool b = (*itA == *itB);
}

在这种情况下,问题是operator==const 。 更改声明,如下所示:

bool operator==(const instruction& rhs) const
                                       ^^^^^^^

尝试将限定符 const 添加到运算符 ==。此外,您没有展示如何声明和使用向量。

你可能想让 operator=() 方法本身变得 const。 您可以通过添加"const"来做到这一点:

struct instruction
{
    int instr;
    int line;
    bool operator==(const instruction& rhs) const  // add const keyword here
    {
        return (instr == rhs.instr) && (line == rhs.line);
    }
};