Initialising Static Variables in C Classes
In object-oriented programming, it's often necessary to initialise static variables within classes. However, this practice can present challenges, as exemplified by the following question:
Dilemma:
A developer has identified several functions within their class that do not require object access and have therefore been marked as static. However, the compiler demands that all accessed variables also be declared static. The developer subsequently declares these variables as static const within the class but encounters compilation errors.
Solution:
To initialise static variables within a class, one should define them within the class declaration but initialise them in a separate source file. This is demonstrated below:
// Class Header class Thing { public: static string RE_ANY; static string RE_ANY_RELUCTANT; }; // Source File string Thing::RE_ANY = "([^\n]*)"; string Thing::RE_ANY_RELUCTANT = "([^\n]*?)";
Alternative Consideration:
It's important to note that making functions static means they are no longer associated with an object and cannot access non-static members. Instead, consider marking them as const, which prevents them from modifying members but allows access to them.
The above is the detailed content of How to Properly Initialize Static Variables in C Classes?. For more information, please follow other related articles on the PHP Chinese website!