问题
I have for example the following code:
#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;
}
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?
Thanks, Kostya
回答1:
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()); }
}
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});
or
Foo f2{1,2,3,4,5};
来源:https://stackoverflow.com/questions/13266249/initializing-stdarray-private-member-through-constructor