Qvector <qstring> </qstring>的扩展初始化列表

时间:2013-05-26 07:12:17

标签: qt vector initializer-list

编译此代码时

QVector<QString> taskTitle({"Movies which are directed by Steven Spilberg",
                           "All those who have reviewed Gone whith the wind",
                           "Summation of Gone with the wind scores",
                           "All years which has a movie whith 5 or 4 scores increasingly sortd"});

编译器给了我:

error: no matching function for call to
   'QVector<QString>::QVector(<brace-enclosed initializer list>)'

我也用过:

QVector<QString> taskTitle={"Movies which are directed by Steven Spilberg",
                           "All those who have reviewed Gone whith the wind",
                           "Summation of Gone with the wind scores",
                           "All years which has a movie whith 5 or 4 scores increasingly sortd"};

再次:

error: in C++98 'taskTitle' must be initialized by constructor, not by '{...}'

我的编译器是MinGW并附带QT 5.0.1 我该怎么办?

1 个答案:

答案 0 :(得分:2)

可能的解决方案

我认为要在MinGW中启用C ++ 11功能,您应该设置适当的标志。有QMAKE_CXXFLAGSqmake设置编译器选项。因此,您的.pro文件应如下所示:

QT       += core
QT       -= gui
QT       += sql

# or c++0x
QMAKE_CXXFLAGS += -std=c++11 

TARGET = untitled
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app

SOURCES += main.cpp

添加细节

此外,Qt具有Q_COMPILER_INITIALIZER_LISTS宏来确定集合是否提供初始化列表构造函数。例如,在QVector

#ifdef Q_COMPILER_INITIALIZER_LISTS
#include <initializer_list>
#endif

template <typename T>
class QVector
{
    // ...

#ifdef Q_COMPILER_INITIALIZER_LISTS
     inline QVector(std::initializer_list<T> args);
#endif

    // ...
};

基于此标志,我们可以创建一个小应用程序来测试使用初始化列表的可行性:

#ifdef Q_COMPILER_INITIALIZER_LISTS
    qDebug("Yes");
#else
    qDebug("No");
#endif

此标志在Qt5的qcompilerdetection.h文件中定义(Qt4为qglobal.h)。例如,对于我有的编译器(它是gcc 4.7.2),以下行将启用C ++ 11功能。

#if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_CLANG)
#  if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
#    if (__GNUC__ * 100 + __GNUC_MINOR__) >= 404
       /* C++11 features supported in GCC 4.4: */
#      define Q_COMPILER_INITIALIZER_LISTS
#    endif
#  endif
#endif

因此,如果通过设置QMAKE_CXXFLAGS无法解决问题,您可以查看此文件并探索为您的编译器集启用了哪些标志。