-1

在“if (size == list[i])”处,“==”上用红色标记,表示No operator "==" matches these operands operand 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";
}
4

2 回答 2

1

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

bool operator==(const size_t& size) const  {
  // Compare
  // As example return m_size == size;
}
于 2018-07-20T10:23:11.610 回答
0

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

size == list[i].size;

或者

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

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

期望是……

3 == list[i];

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

于 2018-07-20T08:22:31.500 回答