"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 Initialize Static `const std::string` Data Members in C++?

How to Initialize Static `const std::string` Data Members in C++?

Published on 2024-12-21
Browse:805

How to Initialize Static `const std::string` Data Members in C  ?

Declaring Static Data Members of Type const std::string

In C , initializing a static data member of type const std::string directly within the class definition is not permitted. Instead, there are two options to define such data members:

Inline Variables (C 17 or Later)

Use an inline variable, which defines and initializes the static member within the class definition:

class A {
private:
  inline static const string RECTANGLE = "rectangle";
};

External Definition

Define the static member outside the class definition and provide the initializer in a separate implementation file:

Header File

class A {
private:
  static const string RECTANGLE;
};

Implementation File

const string A::RECTANGLE = "rectangle";

Limitations of In-Class Initialization

The syntax of initializing static data members within the class definition is only supported for integral and enum types. For non-integral types like const std::string, this approach is not valid.

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