1

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

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 的向量在比较这些元素时没有看到我为我的结构定义的 operator==。

4

3 回答 3

3

您还没有显示实际失败的代码,但很可能是这样的场景:

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

在这种情况下,问题是事实operator==并非如此const。更改声明如下:

bool operator==(const instruction& rhs) const
                                       ^^^^^^^
于 2013-11-06T20:07:26.810 回答
1

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

于 2013-11-06T20:03:54.947 回答
0

您可能希望将 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);
    }
};
于 2013-11-06T20:06:41.567 回答