"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Define Static const std::string Members in C++?

How to Define Static const std::string Members in C++?

Published on 2024-12-21
Browse:693

How to Define Static const std::string Members in C  ?

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.

Latest tutorial More>

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