Reputation: 79
So I'm learning C++ from Stephen Prata book and I want to do one exercise... So the problem is this:
I want to use a std::valarray inside a struct, inside a class like this:
class Wine
{
private:
struct Pair
{
std::valarray<int> valYear;
std::valarray<int> valBottlesNum;
};
int m_yearNum;
Pair m_numericData;
public:
Wine();
Wine(int, const int[], const int[]);
};
And initialize this via member initialization list:
Wine::Wine(int yearNum, const int year[], const int bottlesNum[])
: m_yearNum(yearNum),
m_numericData.valYear(yearNum, year),
m_numericData.valBottlesNum(yearNum, bottlesNum)
{}
But it just doesn't want to work. Somehow compiler does not like this "." to access members of a m_numericData struct in a initializer list.
I could just abandon Pair struct and do valYear and valBottlesNum as a simple class member variables and initilize them like this...
Wine::Wine(, int yearNum, const int year[], const int bottlesNum[])
: m_yearNum(yearNum), m_valYear(yearNum, year), m_valBottlesNum(yearNum, bottlesNum)
{}
but I really want to know how to solve this kinda stuff.
Thanks in adavnce!
Upvotes: 2
Views: 3233
Reputation: 109149
The valarray
constructor you're attempting to use takes a T const*
to the data and an std::size_t
argument indicating the number of array elements that the first argument points to. If you can use C++11, then change yearNum
to std::size_t
and you can use list-initialization, which in turn will aggregate initialize the Pair
.
Wine::Wine(std::size_t yearNum, const int year[], const int bottlesNum[])
: m_yearNum(yearNum)
, m_numericData{{year, yearNum}, {bottlesNum, yearNum}}
{}
Upvotes: 2
Reputation: 37132
You can move the individual initialisations into the body of the constructor:
Wine::Wine(int yearNum, const int year[], const int bottlesNum[])
: m_yearNum(yearNum)
{
m_numericData.valYear = std::valarray<int>(yearNum, year);
m_numericData.valBottlesNum = std::valarray<int>(yearNum, bottlesNum);
}
Alternatively, give Pair
its own constructor.
Upvotes: 2