为什么这两个 Card 对象不等同?
Why do these two Card objects not equate?
我正在实现一个 Card
对象,但我很难理解为什么我的卡片相等性测试失败了。这是声明:
// card.h
namespace Game {
class Card {
public:
int rank; // 1 to 13
char suit;
Card(int r, char s);
~Card();
Card(const Card &other); // copy constructor
friend std::ostream& operator<<(std::ostream& out, const Card &c);
Card &operator=(const Card &c);
bool operator>(const Card &other);
bool operator<(const Card &other);
bool operator<=(const Card &other);
bool operator>=(const Card &other);
bool operator==(const Card &other);
bool operator!=(const Card &other);
};
}
以及实施
//card.cpp
Game {
//...
bool Game::Card::operator==(const Card &other) {
return (this->rank == other.rank) && (this->suit == other.rank);
}
//...
}
在我的测试文件中,它使用 googletest
// CardTests.cpp
#include "gtest/gtest.h"
#include <string>
#include "Card.h"
TEST(CardTests, EqualsOperator) {
Game::Card fourOfHearts1 = Game::Card(4, 'H');
Game::Card fourOfHearts2 = Game::Card(4, 'H');
ASSERT_TRUE(fourOfHearts1 == fourOfHearts2);
}
产生以下输出:
Value of: fourOfHearts1 == fourOfHearts2
Actual: false
Expected: true
为什么两个 fourOfHearts
变量不相等?
(this->suit == other.rank);
中的错字我猜应该是 (this->suit== other.suit);
我正在实现一个 Card
对象,但我很难理解为什么我的卡片相等性测试失败了。这是声明:
// card.h
namespace Game {
class Card {
public:
int rank; // 1 to 13
char suit;
Card(int r, char s);
~Card();
Card(const Card &other); // copy constructor
friend std::ostream& operator<<(std::ostream& out, const Card &c);
Card &operator=(const Card &c);
bool operator>(const Card &other);
bool operator<(const Card &other);
bool operator<=(const Card &other);
bool operator>=(const Card &other);
bool operator==(const Card &other);
bool operator!=(const Card &other);
};
}
以及实施
//card.cpp
Game {
//...
bool Game::Card::operator==(const Card &other) {
return (this->rank == other.rank) && (this->suit == other.rank);
}
//...
}
在我的测试文件中,它使用 googletest
// CardTests.cpp
#include "gtest/gtest.h"
#include <string>
#include "Card.h"
TEST(CardTests, EqualsOperator) {
Game::Card fourOfHearts1 = Game::Card(4, 'H');
Game::Card fourOfHearts2 = Game::Card(4, 'H');
ASSERT_TRUE(fourOfHearts1 == fourOfHearts2);
}
产生以下输出:
Value of: fourOfHearts1 == fourOfHearts2
Actual: false
Expected: true
为什么两个 fourOfHearts
变量不相等?
(this->suit == other.rank);
中的错字我猜应该是 (this->suit== other.suit);