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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 03:48:09976browse

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.

The above is the detailed content of How to Define Static const std::string 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