我想在一个类中初始化一个QHash<...>
。如果代码是在Linux上使用gcc编译的,则没有问题。但是,如果我使用MSVC12,则会出现以下错误:
最小示例:
测试类
#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
测试类
#include "testclass.h"
TestClass::TestClass()
{
}
main.cpp
#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();
}
无题
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会引发此编译器错误以及如何避免该错误吗?
最佳答案
试试这个代码;如果它不起作用,则说明您的编译器不支持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?
但这超出了这个问题的范围,也许对此有所考虑?
关于c++ - 在类中初始化QHash,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59841264/