简体   繁体   English

为什么QCOMPARE(QString(“1”),“1”)导致链接器错误?

[英]Why does QCOMPARE(QString(“1”), “1”) cause a linker error?

I'm exploring Qt's unit test framework, and I noticed an odd thing - considering that QString already implements the equality operator for const char * , I would have expected QCOMPARE(QString("1"), "1") to just work, but instead it causes a linker error: 我正在探索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)

Example code: 示例代码:

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

Why is that? 这是为什么? Doesn't QCOMPARE use the equality operator of the 2 terms? QCOMPARE不使用2项的等式运算符吗?

Edit: Since it was asked in the comments, the project is created by Qt Creator's unit test wizard (File->New Project->Other Project->Qt Unit Test), so of course it has been set up properly, and QT += testlib is included. 编辑:由于在评论中询问,该项目是由Qt Creator的单元测试向导(文件 - >新项目 - >其他项目 - > Qt单元测试)创建的,所以当然它已经正确设置,并且QT += testlib包含QT += testlib

From Qt documentation 从Qt 文档

QCOMPARE is very strict on the data types. QCOMPARE对数据类型非常严格。 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. 这是编译器隐式转换参数时通常会发生的行为。

In source code QCOMPARE looks like 在源代码中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);
}

It is a template which requires first and second argument to be of the same type. 它是一个模板,要求第一个和第二个参数属于同一类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM