2

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!

pmakal
  • 69
  • 1
  • 6

2 Answers2

2

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.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
2

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

Live demo

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • *"and you can use list-initialization"* unless you're using VC++ :~( – Jonathan Potter Mar 25 '15 at 20:09
  • @JonathanPotter Yeah, but they do claim to have fixed it in VS2015, haven't tested it myself. Also, if you haven't installed the VS2013 update where they rolled it back, the code above would compile. But there would be no guarantee it actually did what you wanted :) – Praetorian Mar 25 '15 at 21:13
  • @JonathanPotter and Preatorian Thanks for your answers! And yes, it seems like my Visual Studio doesn't implement this initialization method via initializer list so I had to use assigning `std::valarray` constructor to a member as Jonathan Potter showed. – pmakal Mar 26 '15 at 18:53