Defining Static Data Members of Type const std::string
In C , defining a private static const member of type std::string within a class using in-class initialization, as shown below, is not compliant with the C standard:
class A { private: static const string RECTANGLE = "rectangle"; }
However, C provides alternative approaches to achieve this functionality.
C 17 Inline Variables
Since C 17, you can use inline variables for this purpose. An inline variable is a C 17 feature that allows for the declaration of a static variable directly within the class definition, with the inline keyword. For example:
// In a header file (if necessary) class A { private: inline static const string RECTANGLE = "rectangle"; };
Pre-C 17 Approach
Prior to C 17, you must define the static member outside the class definition and provide the initializer there. Here's an example:
// In a header file (if necessary) class A { private: static const string RECTANGLE; };
// In one of the implementation files const string A::RECTANGLE = "rectangle";
Note: The initialization syntax you attempted (within the class definition) is only supported for integral and enum types.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3