In-Class Initialization of Static Members in C
In C , defining a static member variable inside the class declaration is not permitted. This action results in the compilation error "ISO C forbids in-class initialization of non-const static member `j'".
Reasons for the Prohibition:
Exception for Const Members:
Const static members are allowed to be initialized in the class declaration because they are not modified after initialization. This ensures code efficiency and eliminates the need for explicit initialization.
Implications for Standard Values:
In C, static variables are automatically initialized to 0 if they are not explicitly initialized. However, in C , static variables are not automatically initialized. You must manually initialize them either in the class declaration (for const members) or in a separate .cpp file.
Solution:
To define a non-const static member variable in C , you should initialize it in a separate .cpp file rather than in the class declaration.
For example:
// Header file class Test { public: static int j; }; // .cpp file int Test::j = 0;
The above is the detailed content of Why Can't I Initialize Non-Const Static Members Inside a C Class?. For more information, please follow other related articles on the PHP Chinese website!