通过构造函数初始化std :: array私有成员

mko*_*tya 0 c++ constructor class

我有以下代码:

#include <iostream>
#include <array>

class Base {
public:
  Base() : mA(std::array<int,2>()) {}
  Base(std::array<int,2> arr) : mA(arr) {}
  Base(/* what to write here ??? */);
private:
  std::array<int,2> mA;
};

int main() 
{
    std::array<int,2> a = {423, 12}; // Works fine
    Base b(a); // Works fine
    Base c({10, 20}); // This is what I need. 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我应该如何定义构造函数以允许初始化,如上面"main"中的第3行所示?一般来说,我需要一个可配置的(在编译/运行时长度)结构,允许使用数字列表进行初始化,如{1,2,3}或(1,2,3)或类似的东西,而不需要元素 - 按元素复制.为简单起见,我选择了std :: array,但我担心它可能不适用于这种初始化.你会推荐什么容器?

谢谢,克斯特亚

jua*_*nza 5

您可以添加一个构造函数,该构造函数std::initializer_list<int>将内容复制并复制到数组中:

#include <initializer_list>
#include <algorithm>

....

Base(std::initializer_list<int> a) {
   // check size first
   std::copy(a.begin(), a.end(), mA.begin()); }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果你想在运行时保存一些元素,那么你应该使用一个std::vector<int>这有一个构造函数,initializer_list<int>所以代码更简单:

class Foo {
public:
  Foo() {}
  Foo(const std::vector<int>& arr) : mA(arr) {}
  Foo(std::initializer_list<int> a) : mA(a) {}
private:
  std::vector<int> mA;
};
Run Code Online (Sandbox Code Playgroud)

您可以像这样初始化它:

Foo f1({1,2,3,4,5});
Run Code Online (Sandbox Code Playgroud)

要么

Foo f2{1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)