Home >Backend Development >C++ >How to Initialize Static `const std::string` Data Members in C ?

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

Susan Sarandon
Susan SarandonOriginal
2024-12-16 17:55:161048browse

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.

The above is the detailed content of How to Initialize Static `const std::string` Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn