c – 使用initializer_list初始化数组?

前端之家收集整理的这篇文章主要介绍了c – 使用initializer_list初始化数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > How do I initialize a member array with an initializer_list?5个
这是否可能?
#include <array>
#include <initializer_list>

struct A
{
    A ( std::initializer_list< int > l )
        : m_a ( l )
    {
    }

    std::array<int,2> m_a;
};

int main()
{
    A a{ 1,2 };
}

但是这会导致这个错误

t.cpp: In constructor ‘A::A(std::initializer_list<int>)’:
t.cpp:7:19: error: no matching function for call to ‘std::array<int,2ul>::array(std::initializer_list<int>&)’
         : m_a ( l )
                   ^
t.cpp:7:19: note: candidates are:
In file included from t.cpp:1:0:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: std::array<int,2ul>::array()
     struct array
            ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   candidate expects 0 arguments,1 provided
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: constexpr std::array<int,2ul>::array(const std::array<int,2ul>&)
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   no known conversion for argument 1 from ‘std::initializer_list<int>’ to ‘const std::array<int,2ul>&’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: constexpr std::array<int,2ul>::array(std::array<int,2ul>&&)
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   no known conversion for argument 1 from ‘std::initializer_list<int>’ to ‘std::array<int,2ul>&&’

解决方法

不是这种情况.您可以使用列表初始化程序初始化数组
std::array<int,2> a{1,2};

但是您不能使用initializer_list初始化数组,因为数组只是一个只有默认和复制构造函数的聚合类型.

您可以将阵列留空,然后将initializer_list的内容复制到其中.

原文链接:https://www.f2er.com/c/113503.html

猜你在找的C&C++相关文章