2

我想QHash<...>在一个类中初始化一个。没有问题,如果代码是在linux上用gcc编译的。但是如果我使用 MSVC12,我会收到以下错误:

C2661:QHash<...>::QHash:没有重载函数采用 X 参数

最小的例子:

测试类.h

#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <QHash>
#include <QString>

class TestClass
{
public:
    TestClass();

    QHash<QString, QString> myHash = {{"Hi", "Hello"},
                                      {"test", "Test"}};
};

#endif // TESTCLASS_H

测试类.cpp

#include "testclass.h"

TestClass::TestClass()
{

}

主文件

#include <QCoreApplication>
#include <QDebug>

#include "testclass.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TestClass test;
    qDebug() << test.myHash;

    return a.exec();
}

无标题.pro

QT -= gui

CONFIG += c++11 console
CONFIG -= app_bundle

DEFINES += Q_COMPILER_INITIALIZER_LISTS

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += main.cpp \
    testclass.cpp

HEADERS += \
    testclass.h

你们中有人知道为什么 MSVC 会抛出这个编译器错误以及如何避免这种情况吗?

4

1 回答 1

1

试试这个代码;如果它不起作用,您的编译器不支持 C++11,或者您没有指定正确的编译器标志来启用它。

#include <vector>
#include <iostream>

const std::vector<int> numbers = {1, 2, 3};

int main()
{
    for(auto num: numbers)
    {
        std::cout << num;
    }
}

编译器标志可能是-std=c++11但我不确定 MSVC12

编辑

我无法访问 MSVC12 你可以试试这些吗?我认为它不完全支持 C++11

测试 1

#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <QHash>
#include <QString>

QHash<QString, QString> const myHash = {{"Hi", "Hello"},
                                        {"test", "Test"}};

class TestClass
{
public:
    TestClass();
};

#endif // TESTCLASS_H

测试 2

#ifndef TESTCLASS_H
#define TESTCLASS_H

#include <vector>


class TestClass
{
public:
    TestClass();

    const std::vector<int> numbers = {1, 2, 3};
};

#endif // TESTCLASS_H

编辑

由于测试 1 有效而测试 2 无效,MSVC12 对 C++11 的支持确实有些奇怪。

C++11 声明你应该被允许在头文件中初始化你的类成员变量,但似乎 MSVC 不支持这一点。至少对于初始化列表。

在你最初的问题中,QHash 是 const,现在我不确定你想用这个实现什么,但我相当确定你需要更多的 const,或者你可以将 QHash 作为 X.cpp 文件中的常量你有。也许 QHash 中的字符串也应该是 const 的?

但这超出了这个问题的范围,也许可以考虑一下(?)

于 2020-01-21T12:40:51.267 回答