Trying to define a static constant variable in a class

I define the adc_cmd[9] variable as static const unsigned char in my ADC class under private. Since this is a constant, I thought I would just define it inside the class, but this does not work:

 #pragma once class ADC{ private: static const unsigned char adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 }; //... }; 

Error:

 error: a brace-enclosed initializer is not allowed here before '{' token error: invalid in-class initialization of static data member of non-integral type 'const unsigned char [9]' 

...

Therefore, I tried to infer a string from the class using static const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 }; but this gave this error:

 error: 'static' may not be used when defining (as opposed to declaring) a static data member error: 'const unsigned char ADC::adc_cmd [9]' is not a static member of 'class ADC' 

Obviously, I am not saying this correctly. What is the correct way to declare this?

+3
source share
4 answers

You declare it inside the class body:

 class ADC{ private: static const unsigned char adc_cmd[9]; //... }; 

and define (and initialize) it from the outside (only once, as for any definition of external binding):

 const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 }; 

without a static entry, as indicated by the error message.

(do not ask me for an explanation of why static prohibited here, I always thought that the different rules for repeating qualifiers are completely illogical)

+5
source

In C ++ 03, static definitions of data elements go beyond the class definition.

Title:

 #pragma once class ADC { private: static unsigned char const adc_cmd[9]; }; 

In one .cpp file:

 #include "headername" unsigned char const ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 }; 
+5
source

Combine the two:

 class ADC{ private: static const unsigned char adc_cmd[9]; //... }; //.cpp const unsigned char ADC::adc_cmd[9] = { 0x87, 0xC7, 0x97, 0xD7, 0xA7, 0xE7, 0xB7, 0xF7, 0x00 }; 
+3
source

Just to contribute to Matteo's answer:

It should be noted that the static qualifier is really a bit confusing in C ++. As far as I know, it uses three different things depending on where it is used:

  • Before class attributes: makes this attribute the same for all instances of this class (same as Java).
  • Before a global variable: reduces the scope of the variable only to the current source file (same as for C).
  • Before a local variable inside a method / function, this variable is the same for all calls to this method / function (the same as for C, it can be useful for a singleton design pattern).
+1
source

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


All Articles