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
Release: 2024-12-16 17:55:16
Original
986 people have browsed it

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";
};
Copy after login

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;
};
Copy after login

Implementation File

const string A::RECTANGLE = "rectangle";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template