有没有办法为构造函数使用相同的参数初始化一些对象的数组
Is there a way to initialize a array of some objects with the same parameter for the constructer function?
例如,
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));
演示
相关文章:
- C++转换参数初始化问题
- 构造函数在退出函数时无法初始化一个参数
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- c++构造函数成员初始化:传递参数
- 模板参数列表中的 false 在模板初始化期间计算为什么?
- 构造函数/函数声明参数列表中的统一初始化
- 在构造函数中使用可变参数初始化 std::tuple
- 副本初始化的默认模板参数推导
- 使用向量初始化参数化构造函数的对象数组
- 使用初始化参数的模板类型
- 为什么我的值没有由我的初始化(参数化)构造函数初始化?
- 在声明C 期间具有值的类方法的初始化参数
- 初始化参数时会发生什么?C
- 为什么在C++调用函数时无法初始化参数?
- C++中具有初始化参数的构造函数
- 初始化私有成员数组w/size作为类初始化参数
- 初始化参数 1..[-允许]
- 如何初始化参数化模板类的静态成员
- 在c++中初始化参数化类型数组
- 为什么在使用空引用参数时崩溃,而不是在初始化参数时崩溃?