c++ - 正确编写引用的比较运算符

标签 c++ reference pass-by-reference

我有代码:

#include <vector>

#define DECK_SIZE 52

struct Card {
    int Value;
    int Suit;

    bool operator == (Card &c1) {
        return ((Value == c1.Value) && (Suit == c1.Suit));
    }
};

typedef std::vector<Card> hand_t;

bool IsCardInHand(const Card & checkCard, const hand_t & hand)
{
    for (int i = 0; i < static_cast<int>(hand.size()); ++i) {
        if (checkCard == hand[i]) {
            return true;
        }
    }

    return false;
}

这一行:if (checkCard == hand[i])生成错误:IntelliSense: no operator "==" matches these operands智能感知和 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Card' (or there is no acceptable conversion)编译器 (Visual C++ 2010)。

请帮忙,我该如何重写operator==正确吗?

最佳答案

你需要(注意常量):

bool operator == (const Card &c1) const {

关于c++ - 正确编写引用的比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29490679/

相关文章:

c++ - initializer_list 作为数组引用参数的参数?

javascript - 应用于函数引用/作用域的原型(prototype)继承和函数引用

c++ - C++ 的新运算符是可重入的(或异步安全的)吗?

c++ - 使用 Lua/C++ 设置文件路径

c++ - qwt例子程序意外结束

c++ - 将唯一指针引用保存到唯一指针引用

Java逻辑困惑

java - Java 是 "pass-by-reference"还是 "pass-by-value"?

php - 通过引用传递;为什么原始对象没有改变?

c++ - 将 BSON 数组添加到 MongoDB 3.2 文档并将值提取回来 (MongoCXX 3.2) (C++ 11)