Tell me if you can do this:

struct CMyData { const int size = 100; int array[size]; }; 

I just don’t want to use it in any code for etc. [Magic numbers] , and so it will be clear - it is immediately clear what it is.

Of course, the compiler swears at the current implementation (otherwise I wouldn't ask :)) Is it possible to make the correct version?

  • one
    static const int size = 100; - VTT
  • What is the meaning of the word "static"? You have nothing static in the example. - AnT
  • why not immediately int array [100];? ... But still the best option is a template class. - AR Hovsepyan

1 answer 1

It is not clear what you are trying to do.

The fact that you have a constant member size is a non-static member of a class indicates that its value may differ from one CMyData object to another. The specific value of size will be determined by the CMyData class CMyData . Is this your intention? If yes, then you cannot use such size to specify the size of the array - such size not a constant expression.

If you wanted size always and in all copies of CMyData be exactly 100 , then there is no reason to make size non-static member of a class. Make it static const or, better, static constexpr and all

 struct CMyData { static constexpr int size = 100; int array[size]; }; 
  • Ant, exactly what you wrote I wanted to do. I wanted to do this, thank you so much! And how does constexpr differ from const ? (I ’m reading now - I ’ve never used it before) - Zhihar
  • @Zhihar In this context - no different. In general, constexpr leads to the creation (if possible) of the compile time constant. const generally has no such effect: it simply declares an "immutable object", which is not necessarily a compile-time constant. - AnT