【问题标题】:No operator "==" matches these operands. operand types are: int == type_name`没有运算符“==”与这些操作数匹配。操作数类型是:int == type_name`
【发布时间】:2018-07-20 07:46:53
【问题描述】:

在“if (size == list[i])”处,“==”上的红色标记为No operator "==" matches these operandsoperand types are: int == InventoryRecord。我没有看到我在这里做错了什么。谁能给我解释一下这是为什么?

void linear_search(InventoryRecord list[], int size) {
    int i;

    cout << "\nEnter Element to Search : ";
    cin >> size;

    /* for : Check elements one by one - Linear */
    for (i = 0; i < MAX_SIZE; i++) {
        /* If for Check element found or not */
        if (size == list[i]) {
            cout << "\nLinear Search : Element  : " << size << " : Found :  Position : " << i + 1 << ".\n";
            break;
        }
     }

    if (i == MAX_SIZE)
        cout << "\nSearch Element : " << size << "  : Not Found \n";
}

【问题讨论】:

  • 编译器如何知道如何比较 int 和 InventoryRecord?
  • 很抱歉,由于缺少许多细节,我们可能也看不到您的所作所为。请提供minimal reproducible example
  • 你为什么认为这可行?
  • 您尝试将intInventoryRecord 进行比较。这很难评论,因为您没有显示 InventoryRecord 是如何定义的。但是,与int相比似乎不兼容(正如编译器错误所说)。
  • 停止使用数组,改用std::vector。将更容易使用standard algorithm functions,例如std::find or std::find_if

标签: c++ function struct linear-search


【解决方案1】:

在这种情况下,编译器不知道如何比较这些类型。您可以为 InventoryRecord 类重载 operator==。

bool operator==(const size_t& size) const  {
  // Compare
  // As example return m_size == size;
}

【讨论】:

  • 如果你想要一个比较some_int == some_inventory的表达式,这就是OP正在做的事情。在这种情况下,需要一个非成员 operator==()
【解决方案2】:

list[i] 是 InventoryRecord 类型的项目数组中的第 i 个项目。它不是 InventoryRecord 的大小或可能包含在 InventoryRecord 中的对象的大小。如果 InventoryRecord 是一个类,那么它可能有一个可访问的方法或成员,该方法或成员返回或包含大小。

size == list[i].size;

size == list[i].size();

或者,如果 InventoryRecord 是一个类,您可以考虑添加一个返回大小的 == 运算符。但是,我怀疑这不是您想要的。期望 == 运算符将比较嵌入在 InventoryRecord 中的内容,而不是内容的大小。

期望是……

3 == list[i];

将测试 InventoryRecord 中嵌入的项目是否等于 3。而不是嵌入的项目大小为 3。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2013-01-25
    相关资源
    最近更新 更多