Home >Backend Development >C++ >How Do I Properly Define Static Const Integer Class Members in C ?
Defining Static Const Integer Members in Class Definitions: An Exploration
C allows the declaration of static const integer members within class definitions. However, it's crucial to understand the distinction between initialization and definition in this context.
In the example code provided:
class test { public: static const int N = 10; };
The declaration of N within the class initializes it with a value of 10. However, this is not equivalent to a definition. To resolve the linker error encountered, a separate definition of N is required outside the class definition. This can be achieved through a namespace scope definition, such as:
const int test::N = 10;
Alternately, the constexpr keyword can be used to both declare and define static const integer members in a single step, eliminating the need for a separate definition:
class test { public: static constexpr int N = 10; };
In the case where std::min is called, it expects parameters passed by reference. As N is declared as a static const integer, it needs to be defined to pass the reference requirement. Commenting out the call to std::min allows the code to compile because the definition of N is no longer necessary, although it is still referenced.
In summary, while C allows the initialization of static const integer members within class definitions, a separate definition is necessary for referencing the value. This can be achieved through a namespace scope definition or by using the constexpr keyword.
The above is the detailed content of How Do I Properly Define Static Const Integer Class Members in C ?. For more information, please follow other related articles on the PHP Chinese website!