0

标签中也说明了环境:

GCC 64 位,Qt 5.12

我有以下示例代码:

// test.h

#include <QVector>

class Test 
{
    Test();

    // Same results with QSet
    const QVector<int> things = {
        BANANA,
        RASPBERRY,
        APPLE,
        -2500,
    };

    const int BANANA = -1000;
    const int RASPBERRY = -2000;
    const int APPLE = -3000;
};
// test.cpp

#include <QDebug>
#include "test.h"

Test::Test()
{
    qDebug() << things.contains(APPLE); // false, expected true
    qDebug() << things.contains(-3000); // false, expected true
    qDebug() << things.contains(-2500); // true, expected true
}

我不明白我是否在定义中做错了什么,或者我在 Qt 中遇到了错误。

4

1 回答 1

0

似乎我试图使用尚未定义的常量变量

// test.h

#include <QVector>

class Test 
{
    Test();

    // Moved them above QVector
    const int BANANA = -1000;
    const int RASPBERRY = -2000;
    const int APPLE = -3000;

    const QVector<int> things = {
        BANANA,
        RASPBERRY,
        APPLE,
        -2500,
    };
};
// test.cpp

#include <QDebug>
#include "test.h"

Test::Test()
{
    // Now the tests pass as expected
    qDebug() << things.contains(APPLE); // true, expected true
    qDebug() << things.contains(-3000); // true, expected true
    qDebug() << things.contains(-2500); // true, expected true
}

不是 QT 中的错误!

于 2020-04-10T14:10:29.310 回答