【问题标题】:Vector of structs - not seeing my definition for operator==结构向量 - 没有看到我对 operator== 的定义
【发布时间】:2013-11-18 05:58:53
【问题描述】:

我有一个名为 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==。

【问题讨论】:

    标签: c++ vector struct operators


    【解决方案1】:

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

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

    在这种情况下,问题在于operator== 不是const。修改声明如下:

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

    【讨论】:

      【解决方案2】:

      您可能希望将 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);
          }
      };
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2011-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-14
          • 2019-06-10
          • 2017-02-28
          • 2017-06-13
          相关资源
          最近更新 更多