2

I want equals 2 objects, exactly cards (unit test with gtest). This is my code:

   #include "stdafx.h"
#include <gtest\gtest.h>
#include <vector>

class Card {
public:
    Card(int value, int color) :value(value), color(color) {};
    int returnColor() const { return color; };
    int returnValue() const { return value; };
    bool operator==(const Card &card) {
        return returnValue() == card.returnValue();
    };
private:
    int value;
    int color;
};

class CardTest : public ::testing::Test {
protected:
    std::vector<Card> cards;
    CardTest() { cards.push_back(Card(10, 2));
    cards.push_back(Card(10, 3));
    };
};
TEST_F(CardTest, firstTest)
{
    EXPECT_EQ(cards.at(0), cards.at(1));
}
int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

I have error:

State Error C2678 binary '==': no operator found which takes a left-hand operand of type 'const Card' (or there is no acceptable conversion)

I try overload operator '==', but this not working :/ Maybe, I must go other way? This is my first unit test :D.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
21koizyd
  • 1,843
  • 12
  • 25
  • That error point line 1448 in gtest.h – 21koizyd Dec 30 '16 at 21:02
  • 1
    `bool operator==(const Card &card) const { ...` ? In other words, the function should not only promise not to mutate the reference it is given, it should also promise not to mutate `this`. – Unimportant Dec 30 '16 at 21:07

2 Answers2

4

The equality operator needs to be const:

bool operator==(const Card &card) const {
                                  ^^^^^

For a discussion of const methods, see Meaning of "const" last in a C++ method declaration?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
-1

Try this:

bool operator ==(const Card& card) {
    return returnValue() == card.returnValue();
}

I think you just have the & in the wrong place.