【问题标题】:Compiler error: "Non-aggregates cannot be initialized with initializer list."编译器错误:“无法使用初始化列表初始化非聚合。”
【发布时间】:2016-04-01 15:24:08
【问题描述】:

尝试在 C++ 中创建简单向量时,出现以下错误:

非聚合不能用初始化列表初始化。

我使用的代码是:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char *argv[])
{
    vector <int> theVector = {1, 2, 3, 4, 5};
    cout << theVector[0];
}

我试着说:

CONFIG += c++11 

到我的.pro 文件中,保存并重建它。但是,我仍然遇到同样的错误。我正在使用我认为是 Qt 5.5 的版本,如果这对您有任何意义,那么当我按下 About 时会发生这种情况:Qt's About

感谢任何帮助。

【问题讨论】:

  • 你的目标编译器是什么? VS2013?
  • @Barmar 不是那个的副本; OP 代码是正确的,但问题是如何为 C++11 模式配置编译器
  • @M.M 但那里的答案显示了其他方法来初始化适用于旧 C++ 版本的向量。
  • @R Sahu 我不确定,我有点初学者。我只是使用 QT Creator 并按运行?

标签: c++ qt


【解决方案1】:

下面一行:

vector <int> theVector = {1, 2, 3, 4, 5};

不会编译 C++11 之前的版本。

但是,您可以这样做:

static const int arr[] = {1, 2, 3, 4, 5};
vector<int> theVector (arr, arr + sizeof(arr) / sizeof(arr[0]) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2016-06-23
    相关资源
    最近更新 更多