gpt4 book ai didi

c++ - 为什么 QCOMPARE(QString ("1"), "1") 会导致链接器错误?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:38 24 4
gpt4 key购买 nike

我正在探索 Qt 的单元测试框架,我注意到一件奇怪的事情 - 考虑到 QString 已经为 const char * 实现了相等运算符,我本以为 QCOMPARE(QString( "1"), "1") 正常工作,但它会导致链接器错误:

tst_untitled14test.obj:-1: error: LNK2019: unresolved external symbol "bool __cdecl QTest::qCompare<class QString,char const [2]>(class QString const &,char const (&)[2],char const *,char const *,char const *,int)" (??$qCompare@VQString@@$$BY01$$CBD@QTest@@YA_NABVQString@@AAY01$$CBDPBD22H@Z) referenced in function "private: void __thiscall Untitled14Test::testCase1(void)" (?testCase1@Untitled14Test@@AAEXXZ)

示例代码:

QVERIFY(QString("1") == "1");         // This works.
QCOMPARE(QString("1"), QString("1")); // This works.
// QCOMPARE(QString("1"), "1"); // Causes a linker error!

这是为什么呢? QCOMPARE 不使用这两个项的相等运算符吗?

编辑:既然评论里问了,项目是通过Qt Creator的单元测试向导创建的(File->New Project->Other Project->Qt Unit Test),所以当然它已正确设置,并且包含 QT += teSTLib

最佳答案

来自 Qt documentation

QCOMPARE is very strict on the data types. Both actual and expected have to be of the same type, otherwise the test won't compile. This prohibits unspecified behavior from being introduced; that is behavior that usually occurs when the compiler implicitly casts the argument.

在源代码中QCOMPARE 看起来像

#define QCOMPARE(actual, expected) \
do {\
if (!QTest::qCompare(actual, expected, #actual, #expected, __FILE__, __LINE__))\
return;\
} while (0)

template <typename T>
inline bool qCompare(T const &t1, T const &t2, const char *actual, const char *expected,
const char *file, int line)
{
return compare_helper(t1 == t2, "Compared values are not the same",
toString(t1), toString(t2), actual, expected, file, line);
}

这是一个模板,要求第一个和第二个参数是同一类型。

关于c++ - 为什么 QCOMPARE(QString ("1"), "1") 会导致链接器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29102299/

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