【问题标题】:Correctly write comparison operator for references正确编写引用的比较运算符
【发布时间】:2015-04-07 11:38:21
【问题描述】:

我有代码:

#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 和编译器 (Visual C++ 2010) 的 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Card' (or there is no acceptable conversion)

请帮忙,我怎样才能正确地重写operator==

【问题讨论】:

  • 请注意,一旦您修复了operator==,您可以将IsCardInHand() 改写为return std::find(hand.begin(), hand.end(), checkCard) != hand.end();

标签: c++ reference pass-by-reference


【解决方案1】:

你需要(注意常量):

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

【讨论】:

  • 谢谢 :-) 很明显,我的脑袋漏水 :(
  • 好吧,现在是我所在地区的早晨,所以你可以以此为借口。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多