【问题标题】:No match for operator != (operands types are pointer and object)运算符 != 不匹配(操作数类型为指针和对象)
【发布时间】:2020-02-28 21:37:45
【问题描述】:

我重载了==!= 运算符,并希望后者引用前者,以免重复任何代码。这是我写的:

bool Date :: operator == (const Date & other) const {
    bool are_equal = Year() == other.Year();

    for (int i=0; i<other.NumEvents() && are_equal; i++)
        are_equal = this[i] == other[i];

    return are_equal;
}

bool Date :: operator != (const Date & other) const {
    return !(this == other);
}

这里最大的问题是this 不是Date 而是Date*。有没有办法在没有指针的情况下引用this Date 或使用thisother Date

【问题讨论】:

  • 另外,this[i] == other[i] 几乎肯定不能正确比较 *thisother 是否相等。
  • @Yunnosch - 是的。但它肯定是将Date 与(参考)与可能不是Date 的东西进行比较。除非类 Date 非常不寻常(例如,有一个返回 Dateoperator[](int)),否则编译器也会对此进行诊断。 OP 显然只是从编译器读取最后一条错误消息 - 当所询问的问题得到修复时,可能会回来询问有关“新”错误消息的类似问题。
  • @Peter 我同意(并且确实同意),我可能应该说“真的。而且......”。但现在我发现了我错过的情况......

标签: c++ c++11 pointers operator-overloading this


【解决方案1】:

您需要取消引用this 指针,以便在它所指的Date 对象上调用您的运算符,例如:

bool Date :: operator == (const Date & other) const {
    bool are_equal = ((Year() == other.Year()) && (NumEvents() == other.NumEvents()));

    for (int i = 0; (i < other.NumEvents()) && are_equal; ++i) {
        are_equal = ((*this)[i] == other[i]);
    }

    return are_equal;
}

bool Date :: operator != (const Date & other) const {
    return !((*this) == other);
}

【讨论】:

    【解决方案2】:

    取消引用指针:

    return !(*this == other);
    

    【讨论】:

    • 查看问题上的 cmets 以获取有关您的代码的其他问题的提示。
    【解决方案3】:

    你可以尝试像这样重载!=函数:

    bool Date :: operator != (const Date & other) const {
        return !(*this == other);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 1970-01-01
      • 2016-05-19
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2012-01-04
      相关资源
      最近更新 更多