如何在类内部初始化数组

how can you initialize an array inside of a class?

本文关键字:初始化 数组 内部      更新时间:2023-10-16

在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标准有效。