正确编写引用的比较运算符
Correctly write comparison operator for references
我有代码:
#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==
?
你需要(注意常量):
bool operator == (const Card &c1) const {
我有代码:
#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==
?
你需要(注意常量):
bool operator == (const Card &c1) const {