【问题标题】:Gtest, equals objectGtest,等于对象
【发布时间】:2016-12-31 05:12:55
【问题描述】:

我想要等于 2 个对象,正好是卡片(使用 gtest 进行单元测试)。 这是我的代码:

   #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();
}

我有错误:

状态错误 C2678 二进制“==”:未找到需要 'const Card' 类型的左操作数(或者没有可接受的 转换)

我尝试重载运算符'==',但这不起作用:/ 也许,我必须走另一条路? 这是我的第一个单元测试:D。

【问题讨论】:

  • gtest.h 中的那个错误点第 1448 行
  • bool operator==(const Card &amp;card) const { ... ?换句话说,函数不仅应该承诺不改变它给出的引用,还应该承诺不改变this

标签: c++ c++11 vector googletest


【解决方案1】:

相等运算符需要是const:

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

有关 const 方法的讨论,请参阅 Meaning of "const" last in a C++ method declaration?

【讨论】:

    【解决方案2】:

    试试这个:

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

    我认为你只是把 & 放在了错误的地方。

    【讨论】:

    • 是的,我试试,这和我的解决方案一样
    猜你喜欢
    • 1970-01-01
    • 2011-12-14
    • 2016-03-21
    • 2020-04-04
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2013-08-07
    • 2020-07-27
    相关资源
    最近更新 更多