c++ - 尝试使用 const int std::array 时出错

标签 c++ arrays c++11 initialization constants

<分区>

为什么当我尝试使用 const int std::array 时出现以下错误? 我必须将错误消息中的“<”替换为“<\”才能正确显示:

#include <array>
#include <iostream>

using namespace std;

int main() {
    array<const int, 4> vals;

    return 0;
}

test.cpp: In function ‘int main()’:

test.cpp:7:22: error: use of deleted function ‘std::array::array()’

array<\const int, 4> vals; ^~~~

In file included from test.cpp:1:0: /usr/include/c++/7.3.0/array:94:12: note: ‘std::array<\const int, 4>::array()’ is implicitly deleted because the default definition would be ill-formed: struct array ^~~~~

/usr/include/c++/7.3.0/array:94:12: error: uninitialized const member in ‘struct std::array<\const int, 4>’

/usr/include/c++/7.3.0/array:110:56: note: ‘const int std::array<\const int, 4>::_M_elems [4]’ should be initialized typename _AT_Type::_Type _M_elems; ^~~~~~~~

最佳答案

您打算如何将数组值分配给 const int 元素?您应该在声明期间初始化它们。

#include <array>

using namespace std;

int main() {
    array<const int, 4> vals{1, 2, 3, 4};

    return 0;
}

没有任何初始化,您的示例类似于无效的 const 声明:

const int a;

由于 std::array 本身不能更新,我想下面的代码会更清楚理解。

#include <array>

using namespace std;

int main() {
    const array<int, 4> vals{1, 2, 3, 4};

    return 0;
}

关于c++ - 尝试使用 const int std::array 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49366517/

相关文章:

c++ - 为什么调用这个复制构造函数而不是移动构造函数?

c++ - GCC 错误 : cannot convert 'const shared_ptr<...>' to 'bool' in return

c++ - 在 Windows 上将 Octave 编译为用于开发的共享库需要哪些步骤?

PHP 将空数组转换为字符串

c++ - decltype(function) 作为类成员

arrays - 给定大小为 N 的数组的三个数字的最大乘积

arrays - matlab 有没有像 python 中那样的列表理解?

c++ - 错误 : request for member (maybe you meant to use '->' ? ) 已经使用 '->'

c++ - 在 Qt Creator 中使用 Magick++

c++ - decaf 线程 vs boost 线程 vs omnithreads