I want to initialize a QHash<...>
inside a class. There is no problem, if the code is compiled with gcc on linux. But if I use MSVC12, I get the following error:
C2661: QHash<...>::QHash:no overloaded function takes X parameters
testclass.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
testclass.cpp
#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();
}
untitled.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
Do somebody of you know why MSVC throws this compiler error and how to avoid that?
Try this code; if it doesn't work, your compiler doesn't support C++11 or you didn't specify the correct compiler flag to enable it.
#include <vector>
#include <iostream>
const std::vector<int> numbers = {1, 2, 3};
int main()
{
for(auto num: numbers)
{
std::cout << num;
}
}
The compiler flag might be -std=c++11 But i'm not sure about MSVC12
I don't have access to MSVC12 can you try these? I'm thinking that it doesn't fully support C++11
Test 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
Test 2
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <vector>
class TestClass
{
public:
TestClass();
const std::vector<int> numbers = {1, 2, 3};
};
#endif // TESTCLASS_H
Edit
Since Test 1 works and Test 2 doesn't, there is indeed something odd about MSVC12 support of C++11.
C++11 states that you should be allowed to initialize your class member variables in the header file, but it appears that MSVC doesn't support this. At least for initializer lists.
In your original question the QHash was const, now I'm not sure what you wanted to achieve with this, but I'm fairly certain that you either need more const or you could have the QHash as a constant in the X.cpp file you have. Maybe the strings inside the QHash should be const as well?
But that is outside the scope of this question, maybe have a think about that(?)