Getting "Inconsistent expression as array binding" when const field

I am trying to define a multidimensional array using my constant field as its dimension, but I get a compilation error saying that the expression is not constant. Is there any other way to do this, so I can use the constant field defined in the constructor initialization list as the size of the array?

Translation for the English majority:

class FunctionWave2D : public DisallowedDomainPoints { protected: double th; double l; a double d, dd; const int number_sqrt; //here the constant double **second_derivatives; protected: bool elasticTenstionOnly; public: FunctionWave2D(int number, double elasticModulus, double dampingFactor, double oscillationDampingFactor, double length) :DisallowedDomainPoints(number * LAYER_COUNT), th(elasticModulus), d(dampingFactor), dd(oscillationDampingFactor), elasticTensionOnly(false), l(length/(sqrt(number)-1)), number_sqrt(sqrt(number)) { second_derivatives = new double[number_sqrt][number_sqrt][LAYER_COUNT]; //(...) 
+4
source share
2 answers

An array constraint must be a compile-time constant. The non-static data member const is not a compile-time constant; it gains its value at runtime when the object is constructed.

So basically, if you need to set the size of this array at runtime, you will have to assemble all the parts using operator new[] . Essentially

 int **data_2d = new int*[runtime_size]; for (int i = 0; i < runtime_size; ++i) data_2d[i] = new int[runtime_size]; 

The extension for a 3d array is simple.

+5
source

In C ++, the term "constant expression" specifically refers to an expression whose meaning is known at compile time. This is not the same as the const variable. For example, 137 is a constant expression, but in this code:

 int function(int x) { const int k = x; } 

The value of k not a constant expression, since its value cannot be determined at compile time.

In your case, you have a data item declared as

  const int ilosc_sqrt; //here the constant 

Even if it is marked const , its value is unknown at compile time. It is initialized in the list of initializers as

 ilosc_sqrt(sqrt(ilosc)) 

This value cannot be determined until the program is started, therefore, an error. (Note that the new C ++ 11 constexpr , in particular, is intended to simplify the definition of constant expressions in the source code and provide the ability to more quickly compile compile time with constants.)

To fix this, you will need to either split your initialization into smaller steps:

 drugie_pochodne = new double**[ilosc_sqrt]; for (int i = 0; i < ilosc_sqrt; i++) { drugie_pochodne[i] = new double*[ilosc_sqrt]; for (int j = 0; j < ilosc_sqrt; j++) { drugie_pochodne[j] = new double[ILOSC_WARSTW]; } } 

Or use a library like Boost.MultiArray that supports the syntax of cleaner initialization.

Hope this helps!

+5
source

Source: https://habr.com/ru/post/1487115/


All Articles