正确编写比较运算符以供参考

时间:2015-04-07 11:38:21

标签: 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的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==

1 个答案:

答案 0 :(得分:4)

你需要(注意结果):

bool operator == (const Card &c1) const {
相关问题