有没有办法为构造函数使用相同的参数初始化一些对象的数组

Is there a way to initialize a array of some objects with the same parameter for the constructer function?

本文关键字:初始化 参数 数组 对象 构造函数 有没有      更新时间:2023-10-16

例如,

class JJ
{
public:
    JJ(int c)
    {
        a = c;
    }
    int a;
};

我会写

JJ z[2] = {6,6};

但是对于JJ z[100]来说,我不能写{6,6,6....,6},那我该怎么办呢?

如果std::vector不符合您的需求

std::vector<JJ> v(100, JJ(6));

您可以使用std::array

namespace detail
{
    template <std::size_t N, std::size_t...Is, typename T>
    std::array<T, N> make_array(std::index_sequence<Is...>, const T& t)
    {
        return {{(static_cast<void>(Is), t)...}};
    }
}

template <std::size_t N, typename T>
std::array<T, N> make_array(const T& t)
{
    return detail::make_array<N>(std::make_index_sequence<N>{}, t);
}

然后

std::array<JJ, 100> a = make_array<100>(JJ(6));

演示