通过构造函数初始化std :: array私有成员 [英] Initializing std::array private member through constructor

查看:106
本文介绍了通过构造函数初始化std :: array私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下代码:

#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;
}

应如何定义构造函数以允许进行初始化,如第3行中所示上面的主要?通常,我需要一个可配置的(在编译/运行时的长度)结构,该结构允许使用数字列表进行初始化,例如{1、2、3}或(1、2、3)或类似的东西,而无需使用以下元素:逐元素复制。为了简单起见,我选择了std :: array,但恐怕这种初始化可能无法正常工作。

How should I define constructor to allow initialization with as shown in the 3rd line inside "main" above? In general, I need a configurable (in length in compile / run time) structure that will allow initialization with list of numbers, like {1, 2, 3} or (1, 2, 3) or something similar without need to element-by-element copying. I chose std::array for simplicity, but I'm afraid it might not work with this kind of initialization. What container would your recommend?

谢谢,
Kostya

Thanks, Kostya

推荐答案

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

You could add a constructor that takes an std::initializer_list<int> and copy the contents into the array:

#include <initializer_list>
#include <algorithm>

....

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

注意:如果,您想持有数量的元素在运行时定义,那么您应该使用 std :: vector< int> 。它具有 initializer_list< int> ,因此代码更简单:

Note: If you wanted to hold a number of elements defined at runtime, then you should use a an std::vector<int> This has a constructor from initializer_list<int> so the code is simpler:

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;
};

您可以像这样初始化它:

You can initialize it like this:

Foo f1({1,2,3,4,5});

Foo f2{1,2,3,4,5};

这篇关于通过构造函数初始化std :: array私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆