In the pursuit of defining private static constant strings for classes, such as shape factories, you may encounter a roadblock with C compilers. This is due to restrictions imposed by the C standard. To overcome this challenge and establish a static const string data member, consider the following solutions:
Utilizing inline variables, introduced in C 17, provides a convenient and efficient way to define static const variables:
class A { private: inline static const string RECTANGLE = "rectangle"; };
Pre-C 17 versions necessitate defining the static member outside the class and providing the initializer separately:
class A { private: static const string RECTANGLE; };
const string A::RECTANGLE = "rectangle";
It's important to note that the syntax with an initializer inside the class definition is reserved for integral and enum types only.
While #define may seem tempting for defining constants, it introduces a level of global visibility that may not be desirable. For instance, if the constant is defined in a header file, it will become globally accessible to all parts of the program. This can lead to naming conflicts with different implementations defining the same constant, among other potential issues.
The above is the detailed content of How Can I Define Private Static Constant String Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!