gpt4 book ai didi

c++ - GoogleTest 无法使用自定义比较运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:48 25 4
gpt4 key购买 nike

我想在 Google Test 中对我的 Word 结构进行简单测试。为了使测试代码更简单和更短,我决定编写一个比较运算符(尽管我并不真的需要一个)并且只使用 ASSERT_EQ,根据 the primer .尽管一切看起来都很好,但我收到编译器错误:

/* Word.h */
namespace tgs {

struct Word {
//something here
Word();
virtual ~Word();
bool operator== (Word& rhs);
};
}

/* Word.cpp */
namespace tgs {
bool Word::operator== (Word& rhs){
return true; //there are actual member comparisons here
}
}


/* TextAreaShould_test.cc */
TEST_F(TextAreaShould, DoSomething) {
Word w1, w2;

if(w1 == w2){ //compiles and runs ok
0;
}
ASSERT_EQ(w1, w2); //produces following error
}

编译错误:

[ 86%] Building CXX object CMakeFiles/tests/TextAreaShould.test.dir/tests/TextAreaShould_test.cc.o
/usr/bin/c++ -I/home/nietaki/zpp/TheGameShow_build -I/home/nietaki/zpp/TheGameShow -I/home/nietaki/zpp/TheGameShow/google_mock/include -I/home/nietaki/zpp/TheGameShow/google_mock/gtest/include -I/usr/local/include -o CMakeFiles/tests/TextAreaShould.test.dir/tests/TextAreaShould_test.cc.o -c /home/nietaki/zpp/TheGameShow/tests/TextAreaShould_test.cc
In file included from /home/nietaki/zpp/TheGameShow/tests/TextAreaShould_test.cc:8:
/home/nietaki/zpp/TheGameShow/google_mock/gtest/include/gtest/gtest.h: In function ‘testing::AssertionResult testing::internal::CmpHelperEQ(const char*, const char*, const T1&, const T2&) [with T1 = tgs::Word, T2 = tgs::Word]’:
/ home/nietaki/zpp/TheGameShow/google_mock/gtest/include/gtest/gtest.h:1363: instantiated from ‘static testing::AssertionResult testing::internal::EqHelper<lhs_is_null_literal>::Compare(const char*, const char*, const T1&, const T2&) [with T1 = tgs::Word, T2 = tgs::Word, bool lhs_is_null_literal = false]’
/home/nietaki/zpp/TheGameShow/tests/TextAreaShould_test.cc:112: instantiated from here
/home/nietaki/zpp/TheGameShow/google_mock/gtest/include/gtest/gtest.h:1326: error: no match for ‘operator==’ in ‘expected == actual’
/home/nietaki/zpp/TheGameShow/renderer/textarea/Word.h:25: note: candidates are: bool tgs::Word::operator==(tgs::Word&)

我还尝试将比较运算符放在类之外,而不是作为成员,但这似乎并没有太大的区别。我尝试按照 Primer 做所有事情,但也许有些地方不对。

最佳答案

比较运算符不会更改任何参数,因此它可以是 const,如 Gooogle Test 使用的那样:

struct Word {

Word();
virtual ~Word();
bool operator== (const Word& rhs) const;
};

...一切正常。

关于c++ - GoogleTest 无法使用自定义比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9753842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com