jeudi 20 avril 2017

Initialize const multidimensional array in class initializer list from constructor arguments

I have a class that includes a const 2d array of values, and I want to define this array when I call the constructor. I have been told using const on values that should never be changed is preferred, so I wanted to try it in this case.

class A {
  public:
    A(const int passedArray[2][2]) : memberArray(passedArray) {}
  private:
    const int memberArray[2][2];
};

const int passedArray[][2] = {
  {0,0},
  {0,1}
};

A a(passedArray); // fails with "incompatible types
                  //in assignment of 'const int (*)[2]' to 'const in[2][2]'
A a(&passedArray); // fails

This also fails with const int passedArray[2][2] = ..., with private: const int** memberArray, etc.

I know I have to use an initializer list because a constructor cannot change values of const. Is this possible at all on C++11?

Aucun commentaire:

Enregistrer un commentaire