[英]Initialize QHash inside a class
我想在一个类中初始化一个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 会抛出这个编译器错误以及如何避免这种错误吗?
试试这个代码; 如果它不起作用,您的编译器不支持 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 是常量,现在我不确定你想用这个实现什么,但我很确定你要么需要更多常量,要么你可以在 X.cpp 文件中将 QHash 作为常量你有。 也许 QHash 中的字符串也应该是 const ?
但这超出了这个问题的范围,也许可以考虑一下(?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.