如何在类内部初始化数组
how can you initialize an array inside of a class?
在main中的类之外,我可以初始化一整列int,如下所示:
int array[20] = {0};
它可以工作,并将所有元素设置为零。在一个类中,如果我试图在构造函数中编写相同的代码,它不会接受它。我如何用out初始化它?必须遍历每个单独的元素?
使用fill_n:
class A
{
int array[50];
public:
A(){
std::fill_n(array,50,0)
}
}
带有矢量
class Test
{
private:
std::vector<int> test;
public:
Test(): test(20) {}
};
或阵列
class Test
{
private:
std::array<int, 20> test;
public:
Test() { }
};
#include<iterator>
#include<array>
#include<algorithm>
class Test
{
private:
int arr[20];
std::array<int, 20> test;
public:
Test() {
test.fill(0); //for std::array
std::fill(std::begin(arr),std::end(arr),0); //for c-style array
}
};
std::数组在默认值下不会初始化其成员。所以我们需要调用"fill"方法。这些代码对C++11标准有效。
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在函数内部的声明中初始化数组,并在外部使用它
- 为什么用结构初始化数组需要指定结构名称
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++使用另一个数组和新值初始化数组
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 在 constexpr 构造函数中初始化数组是否合法?
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在构造函数中初始化数组
- 是否可以使用函数返回的值初始化数组
- 使用宏使用额外元素初始化数组
- 在循环中显示不同值的初始化数组
- 如何在macOS中的旧扩展clang和gcc编译器中初始化数组和向量
- 使用可变模板列表初始化数组,并放置new
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 使用 c++ 中的函数初始化数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- C++ 使用变量而不是常量表达式初始化数组
- 在初始化列表中初始化数组的更好方法
- 在可变参数模板类中初始化数组